mc9
mc9

Reputation: 6349

Change value of character pointed by a pointer

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

Answers (1)

Vlad from Moscow
Vlad from Moscow

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

Related Questions