5

I'm getting warning: assignment from incompatible pointer type [enabled by default] when i compile the following code:

int main() {
     int (*aptr) [5] = NULL;
     int arr[5] = {1,2,3,4,5};

     aptr = &arr[0];

     printf("aptr = %p\n arr = %p\n", aptr, &arr[0]);
     return 0;
}

I'm getting the correct output:

aptr = 0xbfcc2c64
arr = 0xbfcc2c64

But why am I getting the warning of incompatible pointer type?

1

2 Answers 2

9

You declared a pointer to the entire array. Why are you trying to make it point to the first element?

If you want to declare your aptr with int (*)[5] type, as in your example, and make it point to arr, then this is how you are supposed to set the pointer value

aptr = &arr;

What you have in your code now is an attempt to assign a int * value to a pointer of int (*)[5] type. These are different types, which is why you get the warning (which is a constraint violation, AKA error, actually).

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply, the warning got removed. Just a small clarification, &arr is the address of the array. &arr[0] is address of 1st element in the array, conceptually both hold the same address.. isn't it? I tried to print the value &arr and &arr[0] which printed out, &arr = 0xbfa092e4 &arr[0] = 0xbfa092e4 Please excuse if is dumb question.
@user2552690: Yes, purely numerically the address of the entire array is always the same as the address of its first element. Yet the types of the pointers are different. As one consequence of that, pointer arithmetic works differently for such pointers, for one example. Try printing &arr + 1 and &arr[0] + 1 and you will see the difference.
One more query. I was expecting that *aptr would give me the value of 1st element in the array. But I require **aptr to get the value of first element in the array. why? aptr = 0xbfdbf7e4 *(aptr) = 0xbfdbf7e4 **(aptr) = 1
@user2552690: Well, that would be the same mistake. aptr is a pointer to the entire array. This means that *aptr is the array itself, not the first element. In other words, *aptr is the same thing as arr. In order to get access to the first elelement you have to do (*aptr)[0] (cf. arr[0]) or **aptr (cf. *arr). There's nothing surprising here: in order to get that aptr you had to use & operator. Now, in order to get back to array you have to "compensate" for that & operator with an extra *.
1

Array name itself give the base address it is not needed to use &arr.Moreover arr[0] represents the value at the first index.

Comments

Your Answer

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.