首页 > 解决方案 > 为什么使用 & 运算符时 char* 和 char[x] 之间的区别很重要

问题描述

以下代码将出现段错误。

char* input = "12.34"; //< this is only to simplify the example.

char buffer[30] = { 0 };
memcpy(buffer, input, strlen(input));

char* part1 = strsep(&buffer, "."); 

下面的代码不会。

char* input = "12.34"; //< this is only to simplify the example.

char buffer[30] = { 0 };
memcpy(buffer, input, strlen(input));

char* ptr = buffer; //< Only diff.
char* part1 = strsep(&ptr , "."); 

当通过引用 ( &) 作为函数参数传递时,为什么 和 之间的区别char**char*[30]重要?

标签: carrayspointers

解决方案


如果您查看 man for strsep,它需要双指针,因为它试图分配指针。

"char *strsep(char **stringp, const char *delim);
...
and *stringp is updated to point past the token"

基本上,如果你有一个数组,你不能只告诉数组的头在一个新的地方。但是,您可以创建指向该数组中任何元素的指针,然后更改指针的值(如果您愿意,可以使其指向不同的元素)。


推荐阅读