gpt4 book ai didi

C 二维数组损坏

转载 作者:太空宇宙 更新时间:2023-11-04 00:35:21 24 4
gpt4 key购买 nike

我遇到了一个问题,我的二维数组正在损坏。考虑这段代码:

int **generate_clique_adjacency_matrix(const formula f) {
int num_terms = f.num_clauses * kVarsPerClause;
printf("\nnum_terms: %d\n", num_terms);

// construct a 2D array of appropriate size
int **compatible = malloc(sizeof(int) * num_terms);
for (int i = 0; i < num_terms; i++) {
compatible[i] = malloc(sizeof(int) * num_terms);
// initialize every cell to 0
for (int j = 0; j < num_terms; j++) {
printf("writing 0 to (%d, %d)\n", i, j);
compatible[i][j] = 0;
}
}

printf("num_terms: %d\n", num_terms);
printf("matrix:\n");
for (int i = 0; i < num_terms; i++) {
printf("row %d: ", i);
for (int j = 0; j < num_terms; j++) {
printf("%d ", compatible[i][j]);
}
printf("\n");
}
exit(0);
}

哪个正在产生令人震惊的输出:

num_terms: 6
writing 0 to (0, 0)
writing 0 to (0, 1)
writing 0 to (0, 2)
writing 0 to (0, 3)
writing 0 to (0, 4)
writing 0 to (0, 5)
writing 0 to (1, 0)
writing 0 to (1, 1)
writing 0 to (1, 2)
writing 0 to (1, 3)
writing 0 to (1, 4)
writing 0 to (1, 5)
writing 0 to (2, 0)
writing 0 to (2, 1)
writing 0 to (2, 2)
writing 0 to (2, 3)
writing 0 to (2, 4)
writing 0 to (2, 5)
writing 0 to (3, 0)
writing 0 to (3, 1)
writing 0 to (3, 2)
writing 0 to (3, 3)
writing 0 to (3, 4)
writing 0 to (3, 5)
writing 0 to (4, 0)
writing 0 to (4, 1)
writing 0 to (4, 2)
writing 0 to (4, 3)
writing 0 to (4, 4)
writing 0 to (4, 5)
writing 0 to (5, 0)
writing 0 to (5, 1)
writing 0 to (5, 2)
writing 0 to (5, 3)
writing 0 to (5, 4)
writing 0 to (5, 5)
num_terms: 6
matrix:
row 0: 22661104 0 22661136 0 0 0
row 1: 0 0 0 0 0 0
row 2: 0 0 0 0 0 0
row 3: 0 0 0 0 0 0
row 4: 0 0 0 0 0 0
row 5: 0 0 0 0 0 0

我的阵列是如何损坏的?显然,第0行的数据应该全为0。我什至尝试添加断言以确保 malloc 成功。这让我抓狂。

最佳答案

这是错误的:

int **compatible = malloc(sizeof(int) * num_terms);

您需要为 n 个指向 int 的指针预留空间(不是为 nint)

更改为

int **compatible = malloc(sizeof(int *) * num_terms);

或者更好

int **compatible = malloc(sizeof(*compatible) * num_terms);

关于C 二维数组损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42732663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com