Reputation: 51
I came through an interesting observation... The code goes like this:
main()
{
int *num[3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("num = %u &num=%u *num = %d &(*num)=%u",num,&num,*num,&(*num));
}
Output:
num = 3216090596 &num = 3216090596 *num = 1 &(*num)=3216090596
what I was trying to do was to print the address of 1st element of first array(i.e. 1)
what I have inferred (correct me if am wrong), num is an array of integer pointers, so when I initialized the array it stored the starting address of the three arrays.
simply num
gives the base address of array num. So what is the address of element 1??
Upvotes: 0
Views: 124
Reputation: 11
What you intialised is simillar to two dimensional array int num[][3].In two dimensional the address of the array and address of the first element will always be same.
Upvotes: 0
Reputation: 409176
The address of the first element of any array is &array[0]
, or array + 0
(or simply array
).
The address of element 1
of any array (i.e. the second element) is &array[1]
or array + 1
.
By the way, when you declare num
you declare it as an array of pointer to integers, that is correct. However you do not initialize it as such, you initialize it as an array of arrays. You can't use an array initializer like { 1, 2, 3 }
and pretend it's a pointer. Your code should not even build.
If you want the array as in the initialize list, you should declare it properly:
int num[][3] = { ... };
Upvotes: 4