我试图使用函数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
答案 0 :(得分:3)
在
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){ /* ... */ }