【问题标题】:How can I change the value where char* is Pointing?如何更改 char* 指向的值?
【发布时间】:2015-08-19 12:27:10
【问题描述】:

我正在使用char* 来存储一些变量值,但存在无法更改其值的问题。如果有人可以提出一种方法......对我来说将是一个救命稻草......

char* year=""; //definition as empty
get_data(){
  year=  //"Here I want to give it another value of another variable(also in char*)"
}

【问题讨论】:

    标签: c pointers


    【解决方案1】:

    简短的回答(不要这样做):

    #include <string.h>
    ...
    strcpy(year, "your new string");
    

    不这样做的原因是您不拥有year 指向的内存。相反,您应该将year 声明为char year[100],这会在堆栈上为您分配内存。然后你可以复制一个字符串进去。

    【讨论】:

      【解决方案2】:
      char year[1024] = {0}; // Null terminated, so empty string.
      get_data() {
          strcpy(year, "some value");
      }
      

      【讨论】:

      • @GustavoMori:回答他们需要知道的东西总是比他们问什么要好。现代学校教育的基础。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2015-09-22
      • 2019-12-28
      • 2020-03-12
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多