I m trying to assign a value to string pointer.It's compiling and running but not printing the correct answer?
char *x = "girl";
*x = x[3];
printf("%s\n",x);
Why it's not printing "lirl" ?
You cannot modify a string literal like that. It is undefined behavior.
You should do this instead:
char x[] = "girl";
x[0] = x[3];
printf("%s\n",x);
This works because "girl" is now an array initializer for x[]. Which is just a short form for:
char x[] = {'g', 'i', 'r', 'l', '\0'};
So this is allowed.
You are trying to change a string literal which is constant, and not possible.
char *x = "girl";
This will be stored in a section of the executable such is the .rodata section, and to which you cannot write.
But instead if you do:
char x[] = "girl";
or
char *x;
x = malloc (sizeof (char) * ENOUGH_MEMORY);
strcpy (x, "girl");
then you can modify the string. In the x[] = "girl" case the string will be stored in the function's local (or global .data section if x is global) stack, and in the malloc case the memory will be allocated you from the heap, and x stores the base address of it. In both the case you can read/write both type of locations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With