user2552690
user2552690

Reputation: 163

Pointer to an array giving incompatible pointer type warning

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?

Upvotes: 5

Views: 5836

Answers (2)

hemanth reddy
hemanth reddy

Reputation: 11

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

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320391

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).

Upvotes: 9

Related Questions