gpt4 book ai didi

c - 为什么使用 & 运算符时 char* 和 char[x] 之间的差异很重要

转载 作者:行者123 更新时间:2023-11-30 16:10:36 24 4
gpt4 key购买 nike

以下代码将出现段错误。

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]事情?

最佳答案

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

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

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

关于c - 为什么使用 & 运算符时 char* 和 char[x] 之间的差异很重要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58846088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com