Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements in array of pointer

Tags:

arrays

c

pointers

I am trying to execute following C program using gcc compiler.

#include <stdio.h>

int main()
{   
    int *a[] = {1,2,3,4,5,6};

    printf("\narr0=%d\n", *a);
    printf("arr1=%d\n", *(a+1));
    printf("arr2=%d\n", *a+2);
    printf("arr3=%d\n", *a+3);
    printf("arr4=%d\n", *a+4);

    return 0;
}

Output:-
arr0=1
arr1=2
arr2=9
arr3=13
arr4=17

I am not able to understand what is happening when I skip parenthesis for *a+2, *a+3, *a+4. For *a+2 it manipulates as :

= *a+2
= *a+(4*2)           4 ->Size of int
= 1+(8)
So, *a+2 = 9

Same way it does for others.

But I am expecting output as following. (?)

arr0=1
arr1=2
arr2=3
arr3=4
arr4=5

I know, the way I have declared array of pointers in not good way to do it.

Can anyone explain what is happening here ?

like image 269
RajendraW Avatar asked Jan 23 '26 20:01

RajendraW


2 Answers

You are declaring a bunch of pointers to invalid addresses, since the small integers are very typically not valid integer pointers. You should be getting compiler warnings for this by the way; it's a good idea to read those and fix them before posting a question here. Or at least mention that you do get warnings.

As soon as you dereference any of these, undefined behavior strikes.

It's good that you never do, all you do is index into the array itself, and print the pointers using the wrong format specifier (you should use %p, not %d).

like image 107
unwind Avatar answered Jan 26 '26 12:01

unwind


Unary * has higher precedence than binary +, so *(a + i) and *a + i are interpreted differently.

*(a + i) is equivalent to a[i]; you're retrieving the i'th element of a, so *(a + 2) would be the same as a[2] which would be 3.

*a + i is equivalent to a[0] + i; since a[0] is type int *, the result of a[0] + i is the value of the i'th pointer to int after a[0]. If sizeof (int *) is 4 and a[0] equals 1, then *a + 1 will be 5, *a + 2 will be 9, etc.

Use the %p conversion specifier to print pointer values:

printf("*a + 2 = %p\n", *a + 2);

If you want to index into an array, use subscript notation (a[i]). Using pointer notation is confusing and error-prone (as you have discovered).

like image 45
John Bode Avatar answered Jan 26 '26 11:01

John Bode