Interview Questions

I am trying to use pointers to manipulate an array of ints

C Interview Questions and Answers


(Continued from previous question...)

I am trying to use pointers to manipulate an array of ints

Q: I'm trying to use pointers to manipulate an array of ints. What's wrong with this code?
int array[5], i, *ip;
for(i = 0; i < 5; i++) array[i] = i;
ip = array;
printf("%d\n", *(ip + 3 * sizeof(int)));
I expected the last line to print 3, but it printed garbage.

A: You're doing a bit more work than you have to, or should. Pointer arithmetic in C is always automatically scaled by the size of the objects pointed to. What you want to say is simply

printf("%d\n", *(ip + 3)); /* or ip[3] -- see Q 6.3 */

which will print the third element of the array. In code like this, you don't need to worry about scaling by the size of the pointed-to elements--by attempting to do so explicitly, you inadvertently tried to access a nonexistent element past the end of the array (probably array[6] or array[12], depending on sizeof(int) on your machine).

(Continued on next question...)

Other Interview Questions