为什么char*无法获得正确的价值?

mit*_*tnk 0 c heap malloc

有人可以帮我解释下面的代码:

为什么char *s没有收到分配的内存点位置foo()

#include <stdio.h>
#include <stdlib.h>

char *foo()
{
    char *s = (char *)malloc(20);
    s = "Hello Heap.";
    return s;
}

void bar(char *s)
{
    s = foo();
    printf("bar: %s\n", s); // Works fine just as expected.
}

int main()
{
    char *s;
    bar(s);
    printf("%s\n", s); // Output some undefined content like `H?}?H??`, other than `Hello Heap.`
}
Run Code Online (Sandbox Code Playgroud)

MOH*_*MED 5

代码已修复

#include <stdio.h>
#include <stdlib.h>

char *foo()
{
    char *s = (char *)malloc(20);
    strcpy(s,"Hello Heap.");
    return s;
}

void bar(char **s)
{
    *s = foo();
    printf("bar: %s\n", *s); // Works fine just as expected.
}

int main()
{
    char *s;
    bar(&s);
    printf("%s\n", s); // Output some undefined content like `H?}?H??`, other than `Hello Heap.`
}
Run Code Online (Sandbox Code Playgroud)

说明:

1)您的代码包含:

char *s = (char *)malloc(20);
 s = "Hello Heap.";
Run Code Online (Sandbox Code Playgroud)

这不好.这样您就不会将"Hello Heap."消息复制到已分配的内存中.实际上,您已将s指针指向已分配的内存,然后将指针指向常量字符串地址

2)您的代码包含

void bar(char *s)
{
    s = foo();
    printf("bar: %s\n", s); // Works fine just as expected.
}
Run Code Online (Sandbox Code Playgroud)

在这个函数s中从函数获取指针(指向已分配内存的指针)foo().但是你没有将s指针地址传递给更高级别的函数leve(main).你必须返回s函数末尾的地址,或者你可以通过输入参数传递指针地址的地址cha ** s