cpointersincompatibletypeerror

What is causing "warning: assignment from incompatible pointer type error"?


I'm trying to experiment here with pointer arithmetic, but I get this warning. I am unable to understand where is this going wrong.

The code is written to play with pointer arithmetic since my basics are weak.

    printf("To Check ptrs \t");
    int var[3]={10,20,30};
    int *ptr,i;
    ptr=var;
    for(i=0;i<3;i++)
    {
       printf("Address is %d \t", ptr);
       printf("Value is %d \t", *ptr);
       ptr++;
    }
    ptr=(int*)&var;
    for(i=0;i<3;i++)
    {
       printf("Address is %d \t", &ptr[i]);
       printf("Value is %d \t", ptr[i]);
    }

ptr_arith.c:14:5: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
  ptr=&var;
     ^

I got the desired output, though. Also, when I use

ptr=(int*) &var; 

,it doesn't give me any error. So if someone can tell me what's causing it to be "incompatible", I'll be thankful.


Solution

  • It is very simple.

    You should arrays decays to pointers in the following way:

    int arr[10];

    arr is of type int *

    &arr[0] - is of type int *

    &arr is of type pointer to the array of 10 integers.

    In your code you shuld use

    ptr = var or ptr = &var[0] as var and &var[0] have the same type as pointer ptr.

    &var different type, thus the warning.