i have been struggling few hours sorts of c tutorials , books related pointers want know if it's possible change char pointer once it's been created.
this have tried:
char *a = "this string"; char *b = "new string"; a[2] = b[1]; // causes segment fault *b[2] = b[1]; // seems work compiler throws error. so there way change values inside strings rather pointer addresses?
thanks
edit:
thanks answers. makes more sense now. makes sense why working fine , other times not working. because i'd pass char pointer , other times char array (the char array worked fine).
when write "string" in source code, gets written directly executable because value needs known @ compile time (there tools available pull software apart , find plain text strings in them). when write char *a = "this string", location of "this string" in executable, , location points to, in executable. data in executable image read-only.
what need (as other answers have pointed out) create memory in location not read only--on heap, or in stack frame. if declare local array, space made on stack each element of array, , string literal (which stored in executable) copied space in stack.
char a[] = "this string"; you can copy data manually allocating memory on heap, , using strcpy() copy string literal space.
char *a = malloc(256); strcpy(a, "this string"); whenever allocate space using malloc() remember call free() when finished (read: memory leak).
basically, have keep track of data is. whenever write string in source, string read (otherwise potentially changing behavior of executable--imagine if wrote char *a = "hello"; , changed a[0] 'c'. somewhere else wrote printf("hello");. if allowed change first character of "hello", , compiler stored once (it should), printf("hello"); output cello!)
Comments
Post a Comment