【发布时间】:2016-09-27 16:03:18
【问题描述】:
我正在尝试编写一个函数,该函数接受路径 (char *) 并将其拆分为基于“/”分隔符的字符串数组。简化代码如下:
int split_path(char * path, char ** out) {
out = NULL;
char * token = strtok(path, "/");
int count = 0;
while(token) {
out = realloc(out, sizeof(char*) * (++count));
out[count-1] = malloc(sizeof(char) * strlen(token)+1);
strcpy(out[count-1], token);
fprintf(stderr, "%s\n", out[count-1]);
token = strtok(NULL, "/");
}
out = realloc(out, sizeof(char*) * (count+1));
out[count] = NULL;
return count;
}
int main(int argc, char * argv[]) {
char path[] = "/home/pirates/are/cool/yeah";
char ** out;
int count = split_path(path, out);
fprintf(stdout, "count: %d\n", count);
fprintf(stderr, "1st: %s\n", out[0]); // segfaults here
return 0;
}
split_path 函数中的所有打印语句都打印完美,输出如下所示:
count: 1, string: home
count: 2, string: pirates
count: 3, string: are
count: 4, string: cool
count: 5, string: yeah
count: 5
1st: ./a.out
[1] 5676 segmentation fault (core dumped) ./a.out
但由于某种原因,当我回到主函数时,双字符数组不再有效。我认为这可能是因为它指向在该 split_path 函数中声明的内存,但我正在执行 strcpy 以将字符串放入其中,因此它不应该指向该函数本地的内存。非常感谢任何帮助。
【问题讨论】:
-
char** split_path(char * path, int* count) { -
我会试一试,但我不知道为什么会有很大的不同。
-
@BLUEPIXY 所说的...或使用 char*** 所以 out 实际上会被更改并返回。
-
效果很好,但为什么呢? out 是一个指针,为什么它不会被改变?我需要另一个级别的指针,比如 char** 吗?
-
您没有访问函数中分配的内存。
标签: c string segmentation-fault malloc strcpy