c中的二维数组更新功能

时间:2017-08-16 09:52:44

标签: c arrays

我试图使用函数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

1 个答案:

答案 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){ /* ... */ }