简体   繁体   中英

Can assign string to char* at runtime

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM