In XCode it says:Thread 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);
}
I am trying to pass a pointer that points to a two dimensional array and initialize this WeightedDirGraph. But I can't run this code. I think there must be some sort of mistake when I am using the pointer, but I don't know what the problem is. Can someone help me? Thanks a lot.
An array is not a pointer, and no amount of casting can change that fact.
*(g+i)
(ie g[i]
) is m[i]
, which is an int[7]
, not an int*
.
When you interpret its first elements as an address, hilarity ensues.
You need to start with an array of pointers, since that can be converted to a pointer to a pointer.
With minimal changes to your code, it might look like this:
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);
The better solution is probably to rethink your implementation and store the data in a one-dimensional std::vector
.
Also, g[i][j]
is much easier to follow than *(*(g+i)+j)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.