Allocate a string array from inside a function in C

后端 未结 2 445
栀梦
栀梦 2021-01-19 10:36

I have a function that scans a file and returns the number of the lines along with the lines in a string array, my function looks like this :

int load_lines(         


        
2条回答
  •  孤独总比滥情好
    2021-01-19 10:40

    When you pass an argument into a function, the function always works on a copy of that argument.

    So in your case, load_lines is working on a copy of _array. The original _array is not modified:

    char** _array = NULL;
    printf("%p\n", _array); // Prints "0x0000"
    line_number = load_lines(inname, _array);
    printf("%p\n", _array); // Prints "0x0000"
    

    To modify _array, you need to pass a pointer to it:

    int load_lines(char* _file, char*** _array){
        ...
        (*array) = malloc (line_number * sizeof(char*));
        ...
        (*array)[line_number] = malloc(strlen(line_buffer) + 1);
    }
    
    char** _array = NULL;
    line_number = load_lines(inname, &_array);
    

    [However, any time you find yourself needing a triple pointer (i.e. ***), it's time to reconsider your architecture.]

提交回复
热议问题