malloc-ating multidimensional array in function

前端 未结 7 1811
傲寒
傲寒 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:25

    Here is your function, fixed:

    int malloc2d(int *** grid, int nrows, int ncols){
        int i;
        *grid = (int**)malloc( sizeof(int *) * nrows);
    
        if (*grid == NULL){
            printf("ERROR: out of memory\n");
            return 1;
        }
    
        for (i=0;i<nrows;i++){
    
            (*grid)[i] = (int*)malloc( sizeof(int) * ncols);
            if ((*grid)[i] == NULL){
                printf("ERROR: out of memory\n");
                return 1;
            }
        }
        printf("Allocated!\n");
        return 0;
    }
    
    int main(int argc, char ** argv)
    {
        int ** grid;
    
        malloc2d(&grid, 10, 10);
        grid[5][6] = 15;
        printf("%d\n", grid[5][6]);
        return 0;
    }
    

    Note the function now recieves an int*** and you pass the address of your int** to the function. The function then dereferences the int*** to put the address of the allocated memory block in it.

    0 讨论(0)
提交回复
热议问题