malloc-ating multidimensional array in function

前端 未结 7 1847
傲寒
傲寒 2020-12-10 22:28

I\'m trying to allocate a 2d array in a C program. It works fine in the main function like this (as explained here):

#include 
#include 

        
7条回答
  •  一个人的身影
    2020-12-10 23:03

    If you still want malloc2d to return a status code, the parameter needs to be of type int***:

    int malloc2d(int *** grid, int nrows, int ncols){
    

    And you need to use *grid to refer to the supplied buffer:

        int i;
        *grid = malloc( sizeof(int *) * nrows);
    
        if (*grid == NULL){
            printf("ERROR: out of memory\n");
            return 1;
        }
    
        for (i=0;i

    Then, when calling malloc2d, pass it the address of an int** to fill in:

    int ** grid;
    
    malloc2d(&grid, 10, 10);
    

提交回复
热议问题