c++错误:指向一个数组的指针。

问题描述 投票:0回答:2

在XCode中,它说:线程1:EXC_BAD_ACCESS (code=1, address=0x3c000003e7)

#include <stdio.h>
#include "Assistance.h"
#define infity 999

using namespace std;
class WeightedDirGraph
{
public:
    WeightedDirGraph();
    WeightedDirGraph(int **g, int size);
    ~WeightedDirGraph();
    void BellmanFord();
    void Display();
protected:
    int size;
    int (*(*graph));

};

WeightedDirGraph::WeightedDirGraph(int **g, int s)
{
    int a[s][s];
    graph=(int **)new int *[s];
    for(int i=0;i<s;++i)
    {
        for(int j=0;j<s;++j)
        {
            printf("%d ",*(*(g+i)+j));      //THIS IS THE LINE OF CODE THAT SEEMS TO BE WRONG
        }
        cout<<endl;
    }
    size=s;  
}



int main()
{

  char vexs[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', };
  int m[7][7] =
    {
      {infity,     60,     50,     50,  infity, infity,  infity},
      {infity, infity, infity, infity,     -10, infity,  infity},
      {infity,    -20, infity, infity,      10, infity,      70},
      {infity, infity,    -20, infity,  infity,    -10,  infity},
      {infity, infity, infity, infity,  infity, infity,      30},
      {infity, infity, infity, infity,  infity, infity,      30},
      {infity, infity, infity, infity,  infity, infity,  infity}
    };
    WeightedDirGraph *g=new WeightedDirGraph((int **)m,7);


}

我试图传递一个指向二维数组的指针,并初始化这个WeightedDirGraph。但我无法运行这段代码。我想一定是我在使用指针时出现了某种错误,但我不知道问题出在哪里。谁能帮帮我?非常感谢。

c++ arrays pointers data-structures
2个回答
1
投票

数组不是一个指针,任何数量的转换都不能改变这个事实。*(g+i) (即 g[i])是 m[i],这是一个 int[7],不是 int*. 当你把它的第一个元素解释为一个地址时,就会出现搞笑的情况。

你需要从一个指针数组开始,因为那是个 可以 被转换为一个指针到一个指针。

如果对你的代码进行最小的改动,它可能会是这样的。

int m[7][7] =
{
  {infity,     60,     50,     50,  infity, infity,  infity},
  {infity, infity, infity, infity,     -10, infity,  infity},
  {infity,    -20, infity, infity,      10, infity,      70},
  {infity, infity,    -20, infity,  infity,    -10,  infity},
  {infity, infity, infity, infity,  infity, infity,      30},
  {infity, infity, infity, infity,  infity, infity,      30},
  {infity, infity, infity, infity,  infity, infity,  infity}
};
int* mp[7] = {m[0], m[1], m[2], m[3], m[4], m[5], m[6]};
WeightedDirGraph *g=new WeightedDirGraph(mp, 7);

更好的解决方案可能是重新思考你的实现 并将数据存储在一个一维的... std::vector. 还有: g[i][j] 比起 *(*(g+i)+j).

© www.soinside.com 2019 - 2024. All rights reserved.