Passing multi-dimensional arrays in C

前端 未结 5 665
無奈伤痛
無奈伤痛 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 02:59

    Here is the working code:

    #include 
    #include 
    #include 
    
    #define ELEMENTS 5
    
    void make(char ***array) {
        char *t = "Hello, World!";
    
        *array = malloc(ELEMENTS * sizeof(char *));
    
        int i;
        for (i = 0; i < ELEMENTS; ++i) {
            (*array)[i] = strdup(t);
        }
    }
    
    int main(int argc, char **argv) {
        char **array;
        make(&array);
    
        int i;
        for (i = 0; i < ELEMENTS; ++i) {
            printf("%s\n", array[i]);
            free(array[i]);
        }
        free(array);
        return 0;
    }
    

    As the other have posted - there was unused size, and strdup allocates memory by itself, and it is nice to free the memory afterwards...

提交回复
热议问题