gpt4 book ai didi

c - 在 C 中定义大型动态二维数组时程序停止

转载 作者:行者123 更新时间:2023-11-30 20:20:50 25 4
gpt4 key购买 nike

我正在尝试使用 malloc 定义两个动态二维数组,这是代码(我知道 M = 118 和 N = 186):

int **Cf;
Cf = (int **) malloc(M * sizeof(int *));
for (i = 0; i < N; i++)
Cf[i] = (int *) malloc(N * sizeof(int));

数组Cf分配内存没有问题。然而,当涉及到 Ct 时,我的程序崩溃了。我调试了代码,发现Ct[i] = (int *) malloc(N * sizeof(int))N=164 时失败这有点奇怪。

最佳答案

关键问题:使用了错误的范围。应该是<M ,不是<N@xing

建议使用sizeof针对引用的对象而不是类型。更容易编码、审查和维护。

请注意,强制转换不是必需的。 @Some programmer dude

int **Cf = malloc(sizeof *CF * M);
assert(Cf);

// M, not N
// for(i=0;i<N;i++){
for(size_t m=0; m < M; m++){

printf("%zu\n", m);
Cf[m] = malloc(sizeof *(Cf[m]) * N);
assert(Cf[m]);
}

代码还使用了m而不是i帮助明确 m索引与 M 一致。

<小时/>

使用calloc()

// int **Cf = malloc(sizeof *CF * M);
int **Cf = calloc(M, sizeof *CF);

// Cf[m] = malloc(sizeof *(Cf[m]) * N);
Cf[m] = calloc(N, sizeof *(Cf[m]));

关于c - 在 C 中定义大型动态二维数组时程序停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44659534/

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