Does the char* already contain a address to the first char in this example?
When we do scanf is the 2nd parameter a real address?
#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.
You may initialize s
by allocating it:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.