2

I am using char* to store some variable values, but there's problem that I can't change its value. 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*)"
}
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90

2 Answers2

0

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. Instead, you should declare year as char year[100], this allocates memory for you on the stack. Then you can copy a string into it.

ytoledano
  • 3,003
  • 2
  • 24
  • 39
-1
char year[1024] = {0}; // Null terminated, so empty string.
get_data() {
    strcpy(year, "some value");
}
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
  • @GustavoMori: it's always better to answer what they need to know than what they're asking. Foundation of modern schooling. – Jonas Byström Aug 24 '15 at 08:13