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).
See, however, question 7.19b.
References:
K&R1 Sec. 5.3 p. 94
K&R2 Sec. 5.4 p. 103
ISO Sec. 6.3.6
H&S Sec. 7.6.2 p. 204