Create 2D array by passing pointer to function in c

后端 未结 3 1127
情书的邮戳
情书的邮戳 2021-01-20 04:55

So I read dozens of examples of passing an 2D array pointer to function to get/change values of that array in function. But is it possible to create (allocate memory) inside

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 05:31

    Forget about pointer-to-pointers. They have nothing to do with 2D arrays.

    How to do it correctly: How do I correctly set up, access, and free a multidimensional array in C?.

    One of many reasons why it is wrong to use pointer-to-pointer: Why do I need to use type** to point to type*?.

    Example of how you could do it properly:

    #include 
    #include 
    
    
    void* create_2D_array (size_t x, size_t y)
    {
      int (*array)[y] = malloc( sizeof(int[x][y]) );
    
      for (size_t i = 0; i < x; ++i) 
      {
        for (size_t j = 0; j < y; ++j) 
        {
          array[i][j] = (int)(i + j);
        }
      }
    
      return array;
    }
    
    void print_2D_array (size_t x, size_t y, int array[x][y])
    {
      for (size_t i = 0; i < x; ++i) 
      {
        for (size_t j = 0; j < y; ++j) 
        {
          printf("%d ", array[i][j]);
        }
        printf("\n");
      }
    }
    
    
    int main (void)
    {
      size_t x = 5;
      size_t y = 3;
    
      int (*arr_2D)[y];
    
      arr_2D = create_2D_array(x, y);
    
      print_2D_array(x, y, arr_2D);
    
      free(arr_2D);
    
      return 0;
    }
    

提交回复
热议问题