[英]How can I change the value where char* is Pointing?
I am using char*
to store some variable values, but there's problem that I can't change its value. 我正在使用
char*
存储一些变量值,但是存在无法更改其值的问题。 If anyone could suggest a method..... Would be a life saver for me.... 如果有人可以建议一种方法.....对我来说将是救生员。
char* year=""; //definition as empty
get_data(){
year= //"Here I want to give it another value of another variable(also in char*)"
}
The short answer (don't do this): 简短的答案(不要这样做):
#include <string.h>
...
strcpy(year, "your new string");
The reason not to do this is that you don't own the memory that year
is pointing to. 不这样做的原因是您不拥有
year
指向的记忆。 Instead, you should declare year
as char year[100]
, this allocates memory for you on the stack. 相反,您应该将
year
声明为char year[100]
,这会在堆栈上为您分配内存。 Then you can copy a string into it. 然后,您可以将字符串复制到其中。
char year[1024] = {0}; // Null terminated, so empty string.
get_data() {
strcpy(year, "some value");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.