Create 2D array by passing pointer to function in c

后端 未结 3 1118
情书的邮戳
情书的邮戳 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条回答
  • 2021-01-20 05:05

    Yes, an array can be initialized this way. As long as you pass a pointer, the memory address should remain the same. So, if you assign anything to the pointer it will valid.

    Think of an a[] as a* pointer to the first element

    a [][] will be a** pointer to a pointer of the first element or a pointer to the first array (first row of a table)

    0 讨论(0)
  • 2021-01-20 05:12

    Yes, passing a pointer to int ** (but 3 stars is considered bad style), I suggest to return an allocated variable from your function:

    int **createArr(int x, int y)
    {
        int **arrPtr;
        int i, j;       //Loop indexes
    
        arrPtr = malloc(x*sizeof(int*));
        if (arrPtr == NULL) { /* always check the return of malloc */
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        for (i = 0; i < x; ++i) {
            arrPtr[i] = malloc(y*sizeof(int));
            if (arrPtr[i] == NULL) {
                perror("malloc");
                exit(EXIT_FAILURE);
            }
        }
        for (i = 0; i < x; ++i) {
            for (j = 0; j < y; ++j) {
                arrPtr[i][j] = i + j;
            }
        }
        return arrPtr;   
    }
    

    Call it using:

    arr = createArr(x, y);
    
    0 讨论(0)
  • 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 <stdio.h>
    #include <stdlib.h>
    
    
    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;
    }
    
    0 讨论(0)
提交回复
热议问题