Reputation: 6349
I would like to know why my code giving me error when run.
I am trying to change the character value pointed by a pointer variable.
#include <stdio.h>
int main() {
char amessage[] = "foo";
char *pmessage = "foo";
// try 1
amessage[0] = 'o'; // change the first character to '0'
printf("%s\n", amessage);
// try 2
*pmessage = 'o'; // This one does not work
printf("%s\n", pmessage);
}
The first attempt works, and prints ooo
. But the second one gives me:
[1] 9677 bus error ./a.out
Any ideas?
Upvotes: 1
Views: 310
Reputation: 310950
In this statement
*pmessage = 'o';
you are trying to change the string literal "foo"
because the pointer is defined like
char *pmessage = "foo";
String literals are immutable in C and C++. Any attempt to change a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
Upvotes: 4