Can I do code such:
char *p;
p = User_input;
Is it possible to assign a string to p
at runtime?
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);
p
point to an existing string by settingp
equal to a pointer to the first character of that string. But before you can get user input, you'll likely need to allocate some memory to get the input into.