1

What would be the value of array and p after executing

int array[] = {1,2,3}, *p = array;

a. *p++;
b. (*p)++;
c. *p++; (*p)++

I know the answer is

a) array = {1,2,3} and *p = 2 
b) array = {2,2,3} and *p = 2
c) array = {1,3,3} and *p = 3

but I just don't understand how. And explanation would be great!

7
  • @mclaassen: I don't think that was the intent. The question specifically asks for the value of p. I think that was an incorrect edit... I think he wants p = array+1 and similar there. Commented Sep 11, 2014 at 20:22
  • Well it matches the results. I think he was clearly interested in the value pointed to by p and not the memory address itself. Commented Sep 11, 2014 at 20:22
  • I'm... not so sure, since the third element of the second array switched to 2 and back. Though I think that was a typo. I begin to think you're correct. Commented Sep 11, 2014 at 20:23
  • Any way you cut it, the shown answer for b is wrong. Commented Sep 11, 2014 at 20:24
  • 1
    The questions states "I know the answer is.." so the question makes a lot more sense if you update it so that the answer really is what is shown. Commented Sep 11, 2014 at 20:24

1 Answer 1

1

p initially points to the first element of the array, so

  • a. Move the pointer to point to the next element, which is 2.
  • b. Dereference p, which is 1, then increase it by 1, which becomes 2.
  • c. The first part is same as a. so the pointer points to the second element, then you dereference it, you get 2, and increase it by 1, you get 3.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.