如何在没有分段错误的情况下将双指针传递给函数C语言 [英] How to pass a double pointer to a function without segmentation fault C language
问题描述
我正在尝试将双指针作为函数的参数传递,但我看不出为什么发生分段错误...
I'm trying to pass a double pointer as an argument to a function and I can't see why the segmentation fault happen...
这是函数:
void create_path_list(char *path_, char ***path) {
// Convert the path (string) into a list of directories
char *token = NULL;
int i = 0;
*path = (char **) realloc(*path, (i + 1) * sizeof(char *));
(*path)[i] = (char *) malloc(2);
strcpy((*path)[0], "/");
for(token = strtok(path_,"/"), i = 1; token != NULL; token = strtok(NULL, "/"), ++i)
{
*path = (char **) realloc(*path, (i + 1) * sizeof(char *));
(*path)[i] = (char *) malloc(sizeof(token) + 1);
strcpy((*path)[i], token);
}
}
主要内容:
int main(){
char **path = NULL;
create_path_list("/dir1/dir2/dir3/file.txt", &path);
return 0;
}
推荐答案
sizeof(token)
将给出令牌的大小,它是一个指针.这样将不会为复制整个字符串分配足够的空间
Will give the size of token, which is a pointer. That will not allocate enough space to copy for the entire string
malloc(sizeof(token) + 1);
strcpy((*path)[i], token);
您应该用strlen替换sizeof
You should replace sizeof with a strlen
您正在将字符串文字传递给函数,然后尝试使用strtok()对其进行更改.您将必须传递一个可变字符串.
You are passing a string literal to you function and then try to change it with strtok(). You will have to pass a mutable string.
char str[] = "/dir1/dir2/dir3/file.txt" ;
create_path_list( str , &path);
我也看不出如何知道指针分配的数组有多大.您将必须返回大小或使用NULL终止数组.
Also I don't see how can you know how large is your allocated array if pointers. You will have to either return the size or NULL terminate the array.
将最后一个元素设置为null:
Set the last element to null:
*path = (char **) realloc(*path, (i + 1) * sizeof(char *));
(*path)[i] = NULL ;
并在函数外部打印
for( size_t i = 0 ; path[i] ; i++ )
{
printf("%s" , path[i] ) ;
}
这篇关于如何在没有分段错误的情况下将双指针传递给函数C语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!