c语言指针的疑惑问题


#include 
void fill(char *p)
{p="opqrst";
}
int main()
{char t[ ]="abcdef";
fill(t);
printf("%s",t);   
}

为什么输出结果是“abcdef”
难道不是将函数的形参指针p的内容变成“opqrst”,之后返回指针p的地址在输出内容应该是“opqrst”?

在函数 fill 中,p 是一个指针变量,它的类型是 char *。指针变量 p 存储的是字符数组 t 的首地址。在函数 fill 中,p 被赋值为字符串常量 "opqrst" 的地址,这意味着 p 变量的值改变了。


但是,这并没有改变数组 t 中的内容。数组 t 仍然包含 "abcdef"。因此,在调用 printf 函数时,输出的仍然是数组 t 中的内容,即 "abcdef"。


要将函数 fill 中的形参 p 的内容变为 "opqrst",需要使用字符数组赋值语句,例如 strcpy 函数,将 "opqrst" 复制到 p 所指向的内存中。例如:

#include <stdio.h>
#include <string.h>

void fill(char *p)
{
    strcpy(p, "opqrst");
}

int main()
{
    char t[ ]="abcdef";
    fill(t);
    printf("%s", t);
}

此时,输出的应该是 "opqrst"。

你改变的仍然只是p的值而非 * p的值
要达到你想要的效果得这样写

#include <stdio.h>
void fill(char** p)
{
    *p = "opqrst";
}
int main()
{
    char *t = "abcdef";
    fill(&t);
    printf("%s", t);
}