I am currently working on a project which uses 2D arrays. I have a function which makes a 2D array of integers, and others that find the shortest path etc, and they all work perfectly.
However, I'm running into issues with another part, where I am getting 'Access Violation errors' when attempting to initialise these arrays:
// |V|x|V| arrays
int** fwdistance = malloc(vertexCount*vertexCount*(sizeof(int)));
int** fwnext = malloc(vertexCount*vertexCount*(sizeof(int)));
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
fwdistance[i][j] = INT_MAX; // Distances = infinity
fwnext[i][j] = -1; // Next nodes are unknown
}
}
Error occurs when attempting to initialise fwdistance[0][0]. As I mentioned, I have other arrays initialised the same way, and they work perfectly:
// Initialises arrays for Dijkstra's Shortest Path algorithm
int *distance = malloc(vertexCount*(sizeof(int)));
int *previous = malloc(vertexCount*(sizeof(int)));
I honestly have no idea!
You allocate a plain array of int
s, but you access it as if it were a jagged array of int
pointers. This causes undefined behavior, which ultimately leads to segmentation fault.
There are two solutions to this problem:
fwdistance
an int*
instead of int**
, and access its elements either with fwdistance[i*vertexCount+j]
or fwdistance[j*vertexCount+i]
, depending on the order you choose, or fwdistance
a pointer to array, ie int (*fwdistance)[vertexCount] = malloc ...
. This approach would let you keep matrix indexing, ie fwdistance[i][j]
. if you wanted to create a 2D array you would have to allocate each row (or column ) separately.
int fwdistance[][] = malloc(vertexCount*sizeof(int*));
for(i=0;i<vertexCount;++i) {
fwdistance[i] = malloc(vertexCount*sizeof(int));
}
...
fwdistance[i][j] = -1;
Alternatively you could emulate a 2d rectangular array by calculating the offset.
int fwdistance[] = alloc(vertexCount*vertexCount*sizeof(int));
...
fwdistance[i*vertexCount+j] = -1;
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.