我试图使用函数Initialize
更新数组distance
的值,下面是我的代码:
#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]);
}
但是打印出来的测试结果显示更新后的数组值是有线的,有人能解释一下这段代码可能发生了什么吗?
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
最佳答案
在
void Initialize(int (*distance)[nodesCount], int nodesCount)
编译器不知道
nodesCount
中的int (*distance)[nodesCount]
是什么,因为它还没有看到它被声明。这应该是void Initialize(int nodesCount, int (*distance)[nodesCount])
然后,您应该将
nodesCount+1
传递到Initialize
函数Initialize(nodesCount+1, distance);
注意,在函数
Initialize
中,必须将<=nodesCount
循环中的每个for
事件更改为<nodesCount
。for (i=0; i<nodesCount; ++i){ /* ... */ }