问题描述
我有扫描文件,并返回一个字符串数组线沿线数的功能,我的功能看起来像这样:
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(char* _file, char** _array){
FILE *infile;
char line_buffer[BUFSIZ];
char line_number;
infile = fopen(_file, "r");
ine_number = 0;
while (fgets(line_buffer, sizeof(line_buffer), infile))
++line_number;
fclose(infile);
_array = malloc (line_number * sizeof(char*));
infile = fopen(_file, "r");
line_number = 0;
while (fgets(line_buffer, sizeof(line_buffer), infile)) {
_array[line_number] = malloc(strlen(line_buffer) + 1);
strcpy(_array[line_number], line_buffer);
//a printf on _array[line_number] works fine here
++line_number;
}
return line_number;
}
当我把它称为是这样的:
When I call it like this:
char** _array;
line_number = load_lines(inname, _array);
_array[0];
我得到一个分段错误,因为该数组似乎对函数的返回后没有分配。
I get a segmentation fault since the array seems to be not allocated after the return of the function.
推荐答案
当你传递一个参数成函数,该函数的总是的工作是在这个参数的副本。
When you pass an argument into a function, the function always works on a copy of that argument.
所以你的情况, load_lines
正在 _array
的副本。原来 _array
不被修改:
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"
要修改 _array
,你需要一个指针传递给它:
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.]
这篇关于从C中的函数内部分配的字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!