gpt4 book ai didi

C 填充二维数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:25 25 4
gpt4 key购买 nike

我正在做一个 C 项目。我需要用数字填充这个数组。但是当我尝试这样的事情时,它会出现段错误。你有什么建议?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
int **my2DArray;

my2DArray = malloc(4 * sizeof(int));

for(int i=0; i<4; i++) {
my2DArray[i] = malloc(5 * sizeof(int));
}

for(int i=0; i<4; i++) {
for(int j=0; j<5; j++) {
my2DArray[i][j] = 1;
}
}

for(int i=0; i<4; i++) {
for(int j=0; j<5; j++) {
printf("%d", my2DArray[i][j]);
}
}

for(int i=0; i<4; i++) {
// error happens here
free(my2DArray[i]);
}

free(my2DArray);
return 0;
}

最佳答案

it gives segmentation error.

sizeof(int) 不是 int **my2DArray 指向的类型的大小。
my2DArray 是一个 pointer to pointer to int从而指向一个int *
可能在 OP 的平台上,int 小于 int*

what is your suggestions?

与其花精力编码匹配类型(并且可能会弄错),不如将大小设置为取消引用的指针。更容易正确编码、审查和维护。

int **my2DArray;

// my2DArray = malloc(4*sizeof(int));
my2DArray = malloc(sizeof *my2DArray * 4); // no type needed
// ^---------------^ // Size of the de-referenced type

健壮的代码会检测分配失败

my2DArray = malloc(sizeof *my2DArray * element_count);
if (my2DArray == NULL && element_count > 0) {
// Handle out-of-memory in some fashion
fprintf(stderr, "Out of memory\n");
exit (EXIT_FAILURE);
}

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

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