Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Pointer error while assigning a value?

Tags:

c

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" ?

like image 853
Dorjay Avatar asked Dec 21 '25 05:12

Dorjay


2 Answers

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.

like image 81
Mysticial Avatar answered Dec 22 '25 20:12

Mysticial


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.

like image 21
phoxis Avatar answered Dec 22 '25 19:12

phoxis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!