Can I do code such:
char *p;
p = User_input;
Is it possible to assign a string to p
at runt开发者_如何学运维ime?
Sure you can, but there is no string
in c, I think you mean char *
, like
char *user_input = malloc(128);
scanf("%s", userinput);
p = user_input;
You have to allocate the memory with malloc. Then you can use strcpy to assign a string to the allocated memory.
Of course you can. Note that this assignment only copies the pointer (the address) to the new variable. It does not copy the string itself.
You have other options if this is not what you ment:
char buf[1000];
strcpy(buf, User_input);
or
char *p;
p = strdup(User_input);
To avoid dangerous buffer overflows with scanf. Use fgets for reading whole line or scanf with a limit specififier "%100s"
for example.
char buffer[128];
scanf("%127s", buffer);
char* my_input = strdup(buffer);
精彩评论