Question:

C programming: array question?

by  |  earlier

0 LIKES UnLike

The array arr and the pointer aPtr are defined as follows

int arr[7] = {3, 6, 9, 12, 15, 18, 21};

int *aPtr ;

As a result of the following two statements what value appears on the screen?

aPtr = arr ;

printf(“%3d\n”, *(aPtr + 4));

a) 9

b) 12

c) 15

d) 18

e) none of the above.

is the answer 12???

 Tags:

   Report

1 ANSWERS


  1. 12 is not the answer.

    aPtr + 4 is the same as aPtr[4]; aPtr[0] = 3, aPtr[4] = 15.

    The only trick to this is pointer arithmetic. Suppose arr is stored beginning at address 0x4000. So, &arr[0] = 0x4000, and after setting aPtr = arr, arr = 0x4000 as well. Simple so far, but (aPtr + 1) does not equal 0x4001. It equals 0x4000 + sizeof(int), normally 4, so (aPtr + 1) = 0x4004 = &arr[1].

    You usually don't have to worry about this, but it can get you into trouble sometimes. E.g., if you did this:

    char *aPtr = (char *)&arr[0];

    printf(“%3d\n”, *(aPtr + 4));

    you would get a different answer. Try it and see what happens.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions