gpt4 book ai didi

c - 使用引用调用时,main 中动态分配的 char 指针不返回字符串

转载 作者:行者123 更新时间:2023-11-30 18:21:29 25 4
gpt4 key购买 nike

我试图通过使用引用调用将 char 指针的地址传递给函数。当我尝试检查 main 和 function 中 char 指针的地址时,它们都是不同的,为什么?我无法理解的一件更令人惊讶的事情是,当使用引用调用时,函数中更新的字符串实际上也应该反射(reflect)在 main 中。

void fun(char *str){
str = "hello";
printf(" str address in fun is = %p\n",str);
printf("In fun str is = %s\n",str);
}
int main(){
char *str = (char*) malloc(sizeof(10));
fun(str);
printf(" str address is = %p\n",str);
printf("In main str is = %s\n",str);
}

程序的输出如下:

str address in fun is = 0x804859b
In fun str is = hello
str address is = 0x839e008
In main str is =

我无法理解为什么会发生这种情况。任何人都可以解释一下这段代码中实际发生了什么。为什么我无法从函数的 main 中更新字符串。[注意:当我使用 int 指针尝试相同的代码时,效果很好。我正在尝试了解堆内存在 char 指针场景中的作用。]

最佳答案

I am not able to understand why this is happening.

由于指针也是按值传递的,所以这一行

str = "hello";

覆盖main传递的值到另一个值,即“hello”字符串文字的位置,持续时间fun 函数调用。这就是为什么您在 fun 中看到正确的打印输出。但是,此重新分配在 main 中不可见。

将此行替换为

strcpy(str, "hello");

将解决该问题。现在两个地址和两个字符串值将相同。

注意:分配 char *str = (char*) malloc(sizeof(10)); 不正确:您不需要 sizeof在那里。它应该是 char *str = malloc(10);

关于c - 使用引用调用时,main 中动态分配的 char 指针不返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42884049/

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