[英]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.