1
#include <stdio.h>
int main(void)
{
  char s[] = {'a','b','c','\n','c','\0'};
  char *p;
  p=&s[3];
  printf("%d\t",++*p++);
  printf("%d",*p);
  return 0;
}  

output: 11 99
Please explain the output. Why there is an increment in the address?

Jens
  • 69,818
  • 15
  • 125
  • 179
Ashwani R
  • 47
  • 2
  • 6

3 Answers3

2

The only thing I see that could possibly be confusing is

++*p++

Postincrement has higher precedence than the dereference operator, so fully parenthesized it looks like

++(*(p++))

Which postincrements p, dereferences the original value of p to get a char, then preincrements the value of the char, and then the new value gets printed by printf as an integer.

So both p and what p is pointing at get incremented.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
0

You should look at the operator precedences.
The expression ++*p++ is evaluated as((*p) + 1) by the compiler, and it also have a side-effect: it increments the value of *p and p. With a ASCII-compatible charset, this instruction prints 11 ('\n'+1 == 10+1 == 11) on the standard output. The second printf call prints the value of s[4] ('c').

md5
  • 23,373
  • 3
  • 44
  • 93
0

pointers in C are just integers which represent a memory location. Arrays in C are always in continuous memory blocks. So when you have a pointer which points to the third element of an array, and you add 1 from the pointer, it points at the fourth element.

In case you are confused about ++*p++: That's because of the different between pre-increment (++p) and post-increment (p++). There is an easy moniker for that for people who hate C++:

"C++ - change the language, return the old problems".

Philipp
  • 67,764
  • 9
  • 118
  • 153