Akhil
Akhil

Reputation: 105

pointer arithemetic: warning: assignment makes pointer from integer without a cast [enabled by default]

I found a following code while learning about pointer arithmetic :

#include <stdio.h>
int main()
{
    int *p, *q, *r, a, b;
    p = &a;
    q = &b;
    p = p-q;             
    r = &a;
    r = (int*)(r-q);   
    printf("p = %p\n",p);
    printf("r = %p\n",r);
}

When I compiled the code I got the following warning:

test.c:7:11: warning: assignment makes pointer from integer without a cast [enabled by   default]
         p = q-p;             
           ^

Now when I run the code, I got the following output:

p = 0x1
r = 0x1

Since the outputs are same, could anyone please explain the significance of the warning. Thank you in advance.

Upvotes: 2

Views: 467

Answers (3)

Anbu.Sankar
Anbu.Sankar

Reputation: 1346

You are subtracting two pointers, it will give you an positive integer but you are storing the result in a pointer.So typecasting is mandatory here...

Do typecast as follows (Typecast must be for result of p-q ,Not for only p)

    p = (int*)(p-q);

By doing typecast like above, you will not get warning...

Upvotes: 0

user694733
user694733

Reputation: 16043

Substracting address from address, doesn't return address. It returns integer, which is a distance between those addresses.

N1570 - 6.5.6p9:

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the stddef.h header. ...

Upvotes: 1

Kapil
Kapil

Reputation: 31

You are subtracting two pointers, it will give you an integer but you are storing the result in a pointer.

Upvotes: 1

Related Questions