我试图使用函数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){ /* ... */ }

07-24 14:32