-3

Question 1:

int main()
{
  char *p="abcd";
  printf("%c",*(p++));
  return 0;
}  // Here it will print a

Question 2:

int main()
{
  char *p="abcd";
  printf("%c",++*(p++));//why it is showing error over here
  return 0;
} // Here it shows runtime error.

Can someone please explain to me why the statement ++*(p++) causes a runtime error.

John Powell
  • 12,253
  • 6
  • 59
  • 67
Dabar Parihar
  • 77
  • 1
  • 3
  • 10

3 Answers3

5
char *p="abcd";

"abcd" is a string literal and string literals are unmodifiable in C. Attempting to modify a string literal invokes undefined behavior.

Use a modifiable array initialized by a string literal to fix your issue:

char p[] ="abcd";
ouah
  • 142,963
  • 15
  • 272
  • 331
  • so which all literals we can modify in c. – Dabar Parihar Jul 06 '14 at 10:36
  • @KerrekSB If you are going to be pedantic, do it with respect to the proper standard. A declaration is not a statement in C. Declarations and statements are neighbors within a compound statement (aka block) (C99 6.8.2:1) – Pascal Cuoq Jul 06 '14 at 10:38
  • @KerrekSB and strictly speaking it is a declaration statement in C++ but in C it is not a statement but a declaration. – ouah Jul 06 '14 at 10:39
  • @PascalCuoq: I was referring to the [C\C++ standard](http://www.cplusplus.com/reference/). :-S – Kerrek SB Jul 06 '14 at 10:44
  • @ouah; *...but in C it is not a statement but a declaration* : I think in C its declaration as well as definition. – haccks Jul 06 '14 at 10:50
  • @haccks it declares and also defines and initializes an object but in the C BNF syntax, it's a declaration. – ouah Jul 06 '14 at 10:59
  • @dabs You can only modify structure literals. To make a modifyable string, initialize an array with a string literal. – fuz Oct 12 '15 at 18:37
2

String literals are read-only. Any attempt to modify it invokes undefined behavior.
In second code you are modifying string literal which causes undefined behavior of the program.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

++*(p++) - This is equivalent to ++*p;p++;

So here first byte value (character) of address stored in variable p is going to increment by 1. And then value of variable p is going to increment, that means p is going to point (store) address of 2nd character of string literal ("abcd").

Now go through the below two variable declaration.

char *p = "abcdef"; 
char p1[] = "abcdef"
  • Here for first variable p, 4 bytes will be allocated in stack to store the address of the string literal "abcdef" and then 6 byte will be allocated to store the string literal ("abcdef") in text segement of process memory. Always text segment is read only. So this value cannot be modifed.

  • Then for second variable 6 byte will be allocated in stack itself to store the string ("abcdef"). Stack segment in process memory has both read and write access.

So performing ++*p (modifying value in address) is applicable for variable p1 but not appilcable for variable p.