Can Anyone explain why I'm getting 1 here?

110 Views Asked by At

it's a pointer arithematic question

    //code   
    #include<iostream>
    using namespace std;
    int main()   
    {
        int a=20,b=50,*p,*q;     
        p=&a;
        q=&b;
        int c=p-q;
        cout<<c;   //Here I'm getting 1 for all positive  value of 'a' and 'b'
        return 0;   
    }

i tried long int c also

2

There are 2 best solutions below

4
On
int c = p - q;

You substracting the values of the pointers p and q itself - actually the addresses of a and b in memory and assign the result to the int c.

If you want to substract the value 20 (a) by 50 (b), you need to dereference the pointers p and q by the * operator to obtain the values of the objects they point to.

Use int c = *p - *q; instead.


If you want to substract the values of the pointers itself, there are to points to consider:

  1. An int is in most cases not capable to hold the number of a memory location. Assigning an number above the range of an int invokes undefined behavior. To store the number of the memory address, you need at least a long int.

  2. The substraction is made by the pointer types itself. Thus, the result of 1.


You need to define c as of type long int and cast both pointers to long int:

#include <iostream>
using namespace std;

int main (void)
{
    int *p, *q;
    int a = 20, b = 50;

    p = &a;
    q = &b;

    long int c = (long int) p - (long int) q;

    cout << c;    
}

Output:

4 (at my execution)

Note that both objects a and b do not need to be stored subsequent in memory. sizeof(int) is not always 4, although it is common for most modern implementations.

0
On

First of all, you are subtracting pointers, not dereferenced pointers. If you were hoping to subtract the value of a from b via your pointers, you need to be using *p and *q.

For the code as written, there is actually no guarantee for what will be output here. In other words, there is no single "correct" answer. You're taking addresses of two automatically allocated variables. The compiler is permitted to put them wherever it wants, so there is no guarantee about how far they lie apart.

Typically though, the compiler will be placing them on the stack, next to one another. So if you subtract their addresses, you'll commonly end up with either 1 or -1.

Note that the types of the pointers are int*, so pointer arithmetic on them will not be in terms of bytes (perhaps that was what you were expecting?) but units of sizeof(int).

Note also that pointer arithmetic beyond a memory "object" isn't strictly well defined according to the standard (see "undefined behaviour"), although most implementations (compilers) don't penalise you for this type of "distance" measurement directly, as it's frequently useful for implementing tree data structures and similar. (At least on modern platforms with linear address spaces.)