This is my code. I want to know what is happening here. Can anybody describe the code?
char *string;
string = "Le Casa de Papel";
*(str+1) = 'a';
return 0;
This is my code. I want to know what is happening here. Can anybody describe the code?
char *string;
string = "Le Casa de Papel";
*(str+1) = 'a';
return 0;
The code snippet has undefined behavior.
The programmer is trying to substitute the second character of the string literal "Le Casa de Papel"
that is 'e'
for the character 'a'
using the pointer arithmetic.
char *string;
string = "Le Casa de Papel";
*(str+1) = 'a';
Note: I think there is a typo and the last statement shall be
*(string+1) = 'a';
that can be rewritten in other way to make it more clear like
string[1] = 'a';
But you may not change a string literal. Any attempt to change a string literal results in undefined behavior.
To make the code valid you should substitute the declaration of the pointer that points to a string literal for an array declaration elements of which are initialized by the string literal as it is shown in the demonstrative program below.
#include <stdio.h>
int main(void)
{
char string[] = "Le Casa de Papel";
puts( string );
*(string + 1 ) = 'a';
puts( string );
return 0;
}
The program output is
Le Casa de Papel
La Casa de Papel
Assuming str
is supposed to be string
, this code is attempting to change the second character in the string from e
to a
, changing "Le Casa de Papel"
to "La Casa de Papel"
. The line
*(str+1) = 'a';
is equivalent to writing
str[1] = 'a';
The problem here is that "Le Casa de Papel"
is a string literal, and attempting to modify the contents of a string literal leads to undefined behavior. String literals are supposed to be immutable - trying to change the value of a string literal should be like trying to change the value of an integer constant, e.g., 1 = 2
- the operation is nonsensical. However, unlike integer constants, string literals have to be stored in memory somewhere, and that memory may or may not be read-only. Attempting to change a string literal may lead to a runtime error, or it may work as expected, or something else may happen - the language definition doesn't require the compiler or runtime environment to handle it in any particular way.