0

Today when learning pointer in C, I have faced a problem. I wrote this code:

#include<stdio.h>

int main()
{
    char *p="XAD";

    printf("%c\n",(*p));
    printf("%c\n",++(*p));
    return 0;
}

First printf() shows correct output and it is X. But for second output, compiler crashes. But why? If (*p) gives 'X'(as expected), then ++(*p) should give 'Y'. Shouldn't it?

Mukit09
  • 2,956
  • 3
  • 24
  • 44

2 Answers2

2

Here:

char *p="XAD";

You create a pointer p and assign it to the string literal "XAD". String literals are immutable, meaning that it cannot be changed. The ++(*p) dereferences the pointer p and increments it, thus attempting to change the contents of the string literal (Specifically, the first character). Attempting to modify a string literal leads to Undefined Behavior as seen in the C11 standard (emphasis mine):

6.4.5 String literals

[...]

  1. 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


Fix the problem by either declaring p as an array or using (*p)+1 instead of ++(*p). Using the former will not modify the contents of the string literal while the latter does.
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
1

The pointer p points to a string literal. Modifying a string literal results in undefined behaviour in C.

Change

char *p="XAD";

to

char p[]="XAD";

which will allow you to modify it since p is an array here.

While char *p="abc"; is perfectly valid in C, in general, string literals should be declared with const keyword as you are not allowed to modify it anyway. This will help catch an accidental change. It should have been of type const char[] but it is of type char [] is because of "historical" reasons (C++ corrected it).

Or you simply interested in printing a modified value, you can do:

printf("%c\n", (*p) + 1);

as suggested by @alk, which does what you code attempts to do but without modifying the string itself.

Community
  • 1
  • 1
P.P
  • 117,907
  • 20
  • 175
  • 238