c - c函数中的二维数组更新

标签 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

最佳答案

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

编译器不知道什么是nodesCountint (*distance)[nodesCount]因为它还没有看到它宣布。这应该是

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

然后,你应该通过 nodesCount+1Initialize功能

Initialize(nodesCount+1, distance);

注意函数Initialize您必须更改每次出现的 <=nodesCountfor循环到 <nodesCount .

for (i=0; i<nodesCount; ++i){ /* ... */ }

关于c - c函数中的二维数组更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45710383/

相关文章:

c - typeof() 表达式中的副作用

php - Yii2 GridView 多维数组

arrays - 什么时候在 Swift 中对数组使用枚举?

javascript - Google 电子表格中的排列/组合

php - 警告 : array_merge(): Argument #2 is not an array Warning: array_merge(): Argument #1 is not an array

我们可以在 C 中使用枚举变量的指针吗

更改 C 中指针所指向的值

c - create系统调用为什么叫creat?

c - 找不到 perl 命令

javascript - 将 array1 的每个元素的属性复制到 array2