C 填充二维数组

标签 c segmentation-fault

我正在做一个 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/

相关文章:

c - 将十六进制值存储到寄存器时出现段错误

c - C 中与 Windows 10 的虚拟端口通信

c - 如何根据条件使用不同的数据类型变量?

python - SWIG void * 参数

c - 我在创建乘法表程序时遇到段错误

c - C中节点的内存分配

c - 检查地址范围是否在进程地址空间中的石蕊测试?

c - 可变参数宏调用 fprintf : how to add arguments to __VA_ARGS__?

c++ - 段错误,使用 MPI 库乘法矩阵

c++ - 就快结束了! C++ 素数筛选套接字