[英]CS50 Week 4 Memory, when we don't reference a address to a string does it come automatically?
Does the char* already contain a address to the first char in this example? char* 是否已经包含此示例中第一个 char 的地址?
When we do scanf is the 2nd parameter a real address?当我们做 scanf 时,第二个参数是真实地址吗?
#include <stdio.h>
int main(void)
{
char *s;
printf("s: ");
scanf("%s", s);
printf("s: %s\n", s);
}
No, and trying to populate it with a call to scanf("%s", s)
is undefined behavior because the pointer does not point to allocated memory.不,并且尝试通过调用
scanf("%s", s)
来填充它是未定义的行为,因为指针不指向已分配的 memory。
You may initialize s
by allocating it:您可以通过分配
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.