简体   繁体   English

可以在运行时将字符串分配给char *

[英]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? 是否可以在运行时将字符串分配给p

Sure you can, but there is no string in c, I think you mean char * , like 当然可以,但是c中没有string ,我认为您的意思是char * ,例如

char *user_input = malloc(128);
scanf("%s", userinput);
p = user_input;

You have to allocate the memory with malloc. 您必须使用malloc分配内存。 Then you can use strcpy to assign a string to the allocated memory. 然后,您可以使用strcpy将字符串分配给分配的内存。

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 . 为了避免用scanf造成危险的缓冲区溢出 Use fgets for reading whole line or scanf with a limit specififier "%100s" for example. 使用fgets读取整行或带有限制说明符"%100s" scanf。

char buffer[128];
scanf("%127s", buffer);
char* my_input = strdup(buffer);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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