-1

Can somebody help me understand this behaviour... ?

I have a snippet like this

#include <stdio.h>
int main()
{
    char *ptr = "Hello";
    printf("%c ",++*ptr);
    return 0;
}

I expected (keeping in mind the precendence order of ++ and * and R to L associativity) that the output should be

I    (the letter I)

but it is not so, rather the program crashes.

so pls somebody explain, what am I missing here?

user3386109
  • 34,287
  • 7
  • 49
  • 68
eRaisedToX
  • 3,221
  • 2
  • 22
  • 28

2 Answers2

1

char *ptr = "Hello";

ptr is string literal and you are not supposed to change it.

If you want to change, use array instead:

char ptr[] = "Hello";
printf("%c ",++*ptr);

Note that in your original code char *ptr = "Hello";, ptr is not a const pointer, it can change to point to something else.

Because the "Hello" string is stored in read-only memory, so as long as ptr is pointing to it, you cannot modify the data pointed by ptr.

Generally, however, you can change ptr to point to somewhere else, and the data pointed by it can be modified, eg,

char *ptr = "Hello";    // data cannot be modified by ptr
char arr[] = "abcd";
ptr = arr;              // data can be modified by ptr
printf("%c ",++*ptr);
artm
  • 17,291
  • 6
  • 38
  • 54
-1

Your code is almost ok, but it needs a slight modification,

#include <stdio.h>
int main()
{
    char *ptr = "Hello";
    printf("%c ",*(++ptr));
    return 0;
}

Explanation : That is happening because according to your code (++*ptr) it will increment the value at the address pointed by ptr, not the ptr itself. But to increment the address stored in ptr we need to increment it first and then dereference that pointer to get the data stored at that value.

SKG
  • 540
  • 1
  • 5
  • 17