Passing multi-dimensional arrays in C

前端 未结 5 656
無奈伤痛
無奈伤痛 2021-01-15 02:45

I am currently trying to learn C and I have come to a problem that I\'ve been unable to solve.

Consider:

#include 
#include 

        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-15 03:18

    You need to pass the address of "array" into the function. That is, you need char ***. This is because you need to change the value of array, by allocating memory to it.

    EDIT: Just to make it more complete, in the function declaration you need to have something like

    void make(char ***array, int *array_size)
    

    Then you need to call it using

    make(&array, &size);
    

    Inside the function make, allocate memory with

    *array = malloc(ELEMENTS * sizeof(char *));
    

    And change other places accordingly.

    Also, as kauppi has pointed out, strdup will allocate memory for you, so you don't need to do malloc on each string.

提交回复
热议问题