gpt4 book ai didi

c - 对指针的引用作为单个指针的参数

转载 作者:行者123 更新时间:2023-11-30 19:12:20 24 4
gpt4 key购买 nike

我试图理解为什么下面的代码不起作用。我意识到我正在尝试将指针引用推送到函数并用其他新地址更改该地址的值。所以第一个指针指向新字符串。问题是为什么这只适用于双指针参数?

#include <stdio.h>


char new_str[] = "This is a new string";


int change_ptr(char * str_ptr)
{
*str_ptr = new_str;
}


int main()
{
char * a_str = "Hello";

change_ptr(&a_str);


return 0;
}

最佳答案

如果您只是传递一个指针,则只会更改该指针中的数据。要更改该数据的位置,您必须使用指向指针的指针。

如果使用 -Wall 标志进行编译,您就会发现此错误。始终启用编译器警告。

在您的情况下,您需要声明您的函数,以便参数是指向指针的指针:

int change_ptr(char ** str_ptr)
{
*str_ptr = new_str;
}

关于c - 对指针的引用作为单个指针的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274865/

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