简体   繁体   English

C中二维数组动态分配时的分段错误

[英]Segmentation fault while dynamic allocation of 2D array in C

I am a newbie to C programming (relearning it after a long time) . 我是C编程的新手(经过很长时间的重新学习)。 I am trying to dynamically allocate memory to a 2D array using malloc. 我正在尝试使用malloc动态地将内存分配给2D数组。 I have tried following the answers on stackoverflow like this and this . 我曾尝试以下像计算器的答案这个这个 But I still get the segmentation fault. 但我仍然得到分段错误。

My code is as below 我的代码如下

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

void allocate2DArray(int **subset, int a, int b)
{
  subset = (int **)malloc( a * sizeof(int *));
  int i,j;

  for(i = 0 ; i < a ; i++)
    subset[i] = (int *) malloc( b * sizeof(int));

  for(i = 0 ; i < a ; i++)
     for(j = 0 ; j < b ; j++)
        subset[i][j] = 0;
}

int main()
{
  int **subset;
  int  a = 4, b = 4;
  allocate2DArray(subset, a, b);
  int i,j;
  for( i = 0 ; i < a  ; i++)
  { 
     for( j = 0 ; j < b ; j++)
     {
        printf("%d ", subset[i][j]);
     }
     printf("\n");
  }
} 

When I comment the lines to print the array, it doens't give any error and program executes without segmentation fault. 当我注释行来打印数组时,它不会给出任何错误,程序执行时没有分段错误。 Please help me understand where I am going wrong. 请帮我理解我哪里错了。

All problems in computer science can be solved by another level of indirection : 计算机科学中的所有问题都可以通过另一层次的间接来解决

void allocate2DArray(int ***p, int a, int b)
{
    int **subset;
    *p = (int **) malloc(a * sizeof(int *));
    subset = *p;

// ...
allocate2DArray(&subset, a, b);

you must pass a int ***subset to the allocation function. 您必须将int ***subset传递给分配函数。 This because arguments are passed by value. 这是因为参数是按值传递的。

You need this: 你需要这个:

void allocate2DArray(int ***subset, int a, int b)

and this: 和这个:

allocate2DArray(&subset, a, b);

By using int **subset; 通过使用int **subset; it does not become 2D array. 它不会成为2D阵列。 It is still 1D storage and just pointer to pointer. 它仍然是1D存储,只是指向指针。

2D array means each element of a pointer buffer must point to a buffer which is suggested by ctn. 2D数组意味着指针缓冲区的每个元素必须指向由ctn建议的缓冲区。 He has suggested ***ptr and *ptr is malloced which created 1st dimension of buffer. 他建议*** ptr和* ptr是malloced,它创建了第一维缓冲区。 Now when you call allocate2DArray() again subset is allocated memory which create second dimension. 现在当你再次调用allocate2DArray()子集时,会分配内存来创建第二个维度。 Which validate my above statement - each element of pointer buffer must point to a buffer. 这验证了我的上述语句 - 指针缓冲区的每个元素都必须指向一个缓冲区。

so now with suggested code - 现在有了建议的代码 -

 *p = (int **) malloc(a * sizeof(int *));

created an array each element of which point to buffer 'subset' which altogether create a true 2D array. 创建了一个数组,每个元素都指向缓冲区“子集”,它们共同创建了一个真正的2D数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM