0

I wrote the following example:

#include <stdio.h>
int main()
{
    int p_arr[4]={3,5,6,1}, q_arr[4]={7,2,9,5};
    int *p=p_arr;
    int *q=q_arr;
    int i=1;
   printf("%d\t", *p + *q);  
   printf("%d\t", *(p++) + *(++q));   
   printf("%d\t", *(++p) + *(q++));
   printf("%d\t", *(p+i) + *q+i);
   printf("%d\t", *p+i + *(q+i));
   return 0;
}

Why is the fourth output 11 and the last output 12?

1
  • 2
    Do you understand * and ++ separately? If yes, what's confusing you?
    – klutt
    Commented Jun 6, 2020 at 16:54

2 Answers 2

1

Pointers in C can be incremented or decremented. In the C semantics, incrementing a pointer means "make it point to the next element, as if the elements are in a array".

To make it even more clear, assume the following setup:

struct s_mystruct
{
    int a;
    double b;
};
struct s_mystruct v[5];
struct s_mystruct *p1 = v;
struct s_mystruct *p2 = v;
struct s_mystruct q1, q2;

Then it is true that *p1 == v[0];, i.e., dereferencing the pointer p1 is the same as accessing the first element of the vector v.

But since p1 is a vector, it can be incremented. It turns out that C has two pointer increment operators: pre-increment and post-increment. So, if:

p1 = v;
p2 = v;
q1 = *(p1++);
q2 = *(++p2);

then it is true that:

q1 == v[0];
q2 == v[1];
p1 == v + 1;
p2 == v + 1;

In other words, both statements increment the value of a pointer, and in the end, the pointer will be pointing to the next element, but p++ means "use the value that the pointer p had before incrementing it, and ++p means "use the value that the pointer p will have after it has been incremented.

0

Hopefully a little extra output will make things self-explanatory.

int main(void) {
  int p_arr[4] = {3, 5, 6, 1}, q_arr[4] = {7, 2, 9, 5};
  int *p = p_arr;
  int *q = q_arr;
  int i = 1;
  printf("\t");
  printf("i:%d p:%p,%d q:%p,%d\n", i, p, *p, q, *q);
  printf("%d\t", *p + *q);
  printf("i:%d p:%p,%d q:%p,%d\n", i, p, *p, q, *q);
  printf("%d\t", *(p++) + *(++q));
  printf("i:%d p:%p,%d q:%p,%d\n", i, p, *p, q, *q);
  printf("%d\t", *(++p) + *(q++));
  printf("i:%d p:%p,%d q:%p,%d\n", i, p, *p, q, *q);
  printf("%d\t", *(p + i) + *q + i);
  printf("i:%d p:%p,%d q:%p,%d\n", i, p, *p, q, *q);
  printf("%d\t", *p + i + *(q + i));
  printf("i:%d p:%p,%d q:%p,%d\n", i, p, *p, q, *q);
  return 0;
}

Output

    i:1 p:0xffffcaf0,3 q:0xffffcae0,7
10  i:1 p:0xffffcaf0,3 q:0xffffcae0,7
5   i:1 p:0xffffcaf4,5 q:0xffffcae4,2
8   i:1 p:0xffffcaf8,6 q:0xffffcae8,9
11  i:1 p:0xffffcaf8,6 q:0xffffcae8,9
12  i:1 p:0xffffcaf8,6 q:0xffffcae8,9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.