Allocate a string array from inside a function in C

后端 未结 2 449
栀梦
栀梦 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:41

    If you want to return a newly allocated array of strings from the function, then the second argument of the function must have a type of char***, eg. a pointer to an array of strings:

    int load_lines(char* _file, char*** _array) {
        ...
        char** tmparray = malloc(line_number * sizeof(char*));
        ...
            tmparray[line_number] = malloc(strlen(line_buffer) + 1);
            strcpy(tmparray[line_number], line_buffer);
        ...
        (*_array) = tmparray;
    }
    

    And when you call the function:

    char** _array;
    line_number = load_hosts(inname, &_array);
    

提交回复
热议问题