How to modify an initialised string
Hi,
here is small segment of code: Code:
#include <stdio.h> Code:
*(src+0)='L'; And, how to change the content of the above string?? Thanks in advance Dileep |
you're derefrencing it. meaning when you change src[0] to L, you're actually changing the first part of the address it points to. when you call printf, printf tries to print from some nonexistant address, and you segfault.
try changing it to: src[0]='L' |
#include <stdio.h>
main() { char *src="linux"; src[0]='L'; printf("%s",src); } This code gives me a segfault... |
erm, what are you compiling it with?
If it's strict it might be worth adding in return 0; |
gcc 3.4.2
Well, this _does_ segault too: #include <stdio.h> int main() { char *src="linux"; src[0]='L'; printf("%s",src); return 0; } |
A preinitialized string is a constant. At least, we shouldn't modify it because it points to a data area that's not writable by us (I think). This works:
#include <stdio.h> main() { char *src = malloc(6); strcpy(src, "linux"); printf("%s\n", src); *(src+0)='L'; printf("%s\n", src); return 0; } So it's not actually a problem with Linux, but with the program itself.. |
All times are GMT -5. The time now is 10:32 AM. |