Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to an array giving incompatible pointer type warning

Tags:

c

pointers

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?

like image 272
user2552690 Avatar asked Jul 05 '13 07:07

user2552690


2 Answers

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

like image 65
AnT Avatar answered Nov 15 '22 00:11

AnT


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

like image 27
hemanth reddy Avatar answered Nov 15 '22 00:11

hemanth reddy