Chen Phillis Chen Phillis - 1 year ago 74
C Question

2D array update in function in c

I was trying to use the function

Initialize
to update the value of array
distance
, here is my code:

#include <stdio.h>
#define NOT_CONNECTED -1

int nodesCount;

void Initialize(int (*distance)[nodesCount], int nodesCount) {
int i, j;
for(i = 0; i <= nodesCount; ++i) {
for(j = 0; j <= nodesCount; ++j) {
distance[i][j] = NOT_CONNECTED;
}
distance[i][i] = 0;
}
for(int i = 0; i <= nodesCount; i++)
printf("distance[%d] = %d\n", i, distance[i][i]);

}

int main() {
scanf("%d", &nodesCount);

int distance[nodesCount + 1][nodesCount + 1];
Initialize(distance, nodesCount);

for(int i = 0; i <= nodesCount; i++)
printf("distance[%d] = %d\n", i, distance[i][i]);
}


But the test result printed out shows the updated array value is wired, could anybody explain what might have happened to this code?

distance[0] = 0
distance[1] = 0
distance[2] = 0
distance[3] = 0
distance[4] = 0
distance[5] = 0
distance[0] = 0
distance[1] = -1
distance[2] = -1
distance[3] = -1
distance[4] = -1
distance[5] = 32677

Answer Source

In

void Initialize(int (*distance)[nodesCount], int nodesCount) 

compiler has no idea what is nodesCount in int (*distance)[nodesCount] because it has not seen it yet declared. This should be

void Initialize(int nodesCount, int (*distance)[nodesCount]) 

Then, you should pass nodesCount+1 to Initialize function

Initialize(nodesCount+1, distance);

Note that in function Initializeyou have to change every occurrence of <=nodesCount in for loops to <nodesCount.

for (i=0; i<nodesCount; ++i){ /* ... */ }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download