int main()
{
char *x = "HelloWorld";
char y[] = "HelloWorld";
x[0] = 'Z';
//y[0] = 'M';
return 0;
}
In the above program, HelloWorld
will be in read-only section(i.e string table). x
will be pointing to that read-only section, so trying to modify that values will be undefined behavior.
But y
will be allocated in stack and HelloWorld
will be copied to that memory. so modifying y will works fine. String literals: pointer vs. char array
Here is my Question:
In the following program, both char *arr
and char arr[]
causes segmentation fault if the content is modified.
void function(char arr[])
//void function(char *arr)
{
arr[0] = 'X';
}
int main()
{
function("MyString");
return 0;
}
Please share your knowledge.
function("MyString");
is similar to
char *s = "MyString";
function(s);
"MyString"
is in both cases a string literal and in both cases the string is unmodifiable.
function("MyString");
passes the address of a string literal to function
as an argument.
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