CS50 第 4 周内存,当我们不引用字符串的地址时它会自动出现吗?

CS50 Week 4 Memory, when we don't reference a address to a string does it come automatically?

本例中的 char* 是否已经包含指向第一个字符的地址?

当我们执行scanf时,第二个参数是真实地址吗?

#include <stdio.h>

int main(void)
{
    char *s;
    printf("s: ");
    scanf("%s", s);
    printf("s: %s\n", s);
}

不,尝试通过调用 scanf("%s", s) 来填充它是未定义的行为,因为指针不指向分配的内存。

您可以通过分配来初始化s

    s = malloc(100);
    if(NULL == s)
    {
         goto cleanup; // one of the few valid uses of goto in C
    }
     
    if(scanf("%99s", s) != 1) 
    {
        // scanf failed to populate 's'
        goto cleanup;
    }

    printf("Hello %s\n", s);
    
cleanup:
    free(s);
    s = NULL;