[英]How can I change the value where char* is Pointing?
我正在使用char*
存储一些变量值,但是存在无法更改其值的问题。 如果有人可以建议一种方法.....对我来说将是救生员。
char* year=""; //definition as empty
get_data(){
year= //"Here I want to give it another value of another variable(also in char*)"
}
简短的答案(不要这样做):
#include <string.h>
...
strcpy(year, "your new string");
不这样做的原因是您不拥有year
指向的记忆。 相反,您应该将year
声明为char year[100]
,这会在堆栈上为您分配内存。 然后,您可以将字符串复制到其中。
char year[1024] = {0}; // Null terminated, so empty string.
get_data() {
strcpy(year, "some value");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.