c语言 - CS50 第 4 周 内存,当我们不将地址引用到字符串时,它会自动出现吗?



在这个例子中,char*是否已经包含了第一个字符的地址?

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

#include <stdio.h>
int main(void)
{
char *s;
printf("s: ");
scanf("%s", s);
printf("s: %sn", 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 %sn", s);

cleanup:
free(s);
s = NULL;

最新更新