Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "pointer to array 10 of int"?

Tags:

c

I have the following code:

#include<stdio.h>

int main()
{
    int(* a)[10];  //declare a as pointer to array 10 of int
    int b[10];    // taken a array of 10 int
    b[2]=32;       
    a=&b;      
    printf("b is on %p\n",&b);
    printf("a is on %p\n",a);
    printf("magic is %d\n",a[2]); // why this is not showing 32
    return 0;
}

output:

b is on 0xbfa966d4
a is on 0xbfa966d4
magic is -1079417052

Here I have taken a as pointer to array 10 of int which points to the array b, so now why am I unable to get the value of 32 on a[2]?

a[2] is evaluated as *(a+2) so now a has address of array b so *(b+2) and *(a+2) are similar so why am I not getting value 32 here?


Edit : i got answer by using

(*a)[2]

but i am not getting how it works ... see when

a[2] is *(a+2) and a+2 is a plus 2 * sizeof(int[10]) bytes.

this way (*a)[2] how expand?

like image 745
Jeegar Patel Avatar asked Feb 16 '12 09:02

Jeegar Patel


1 Answers

Since a is already a pointer, you have to dereference it in order to refer to the array that it points to:

(*a)[2]
like image 182
Blagovest Buyukliev Avatar answered Oct 03 '22 05:10

Blagovest Buyukliev