0

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??

Suvarna Pattayil
5,2555 gold badges35 silver badges60 bronze badges
asked May 8, 2013 at 8:32
0

2 Answers 2

4

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] = { ... };
answered May 8, 2013 at 8:36
Sign up to request clarification or add additional context in comments.

4 Comments

The OP's code doesn't compile and give a lot of warnings.Is something like int *num={3,8,9} even valid?I tried it and it shows warnings.I've posted it in a question just now.
That's fine. I was just trying out different possibilities. In the above case what happened is num[0] gave me the value 1, which is the value of 0th element of the first array. Similarly num[1] gave 4. So my question is "num being an array of pointers to integer should store address of integers at num[0] or num[1] but it is storing values!!"
Similar kind of thing happens when u initilise as char *arr[3]={{'H','I'},{'B','y','e'},{'D','I','E'}};
but in case of strings like char *arr[3]={"hi","bye","die"}; arr[0] gives address of 'h' of the string "hi"
0

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.

answered May 8, 2013 at 12:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.