Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer/Address difference [duplicate]

Why is the difference between the two addresses wrong? http://codepad.org/NGDqFWjJ

#include<stdio.h>
int main()
{
   int i = 10, j = 20;
   int *p = &i;
   int *q = &j;
   int c = p - q;
   printf("%d\n", p);
   printf("%d\n", q);
   printf("%d", c);
   return 0;
}

Output:

-1083846364
-1083846368
1
like image 861
Ava Avatar asked Mar 24 '12 20:03

Ava


People also ask

What is the difference between pointer and address?

A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address.

Does the address of a pointer change?

You can't change the address of a pointer (or of any variable). Once you declare the variable, it's address is firmly set, once and forever. You can, however, change the value of a pointer, just as easily as you can change the value of an int: x = 10 or p = &t.

What is the difference between pointer and double pointer?

So, when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.

How do you find the difference between two pointers?

The subtraction of two pointers gives the increments between the two pointers. For Example: Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are subtracted. The difference between address is 16 bytes.


1 Answers

First, pointer arithmetic isn't defined when performed on unrelated pointers.

Second, it makes sense. When subtracting pointers you get the number of elements between those addresses, not the number of bytes.

If you were to try that with

char *p1 = &i, *p2 = &j;

you would get a different result.


As a side note, use %p when printing pointers.

like image 106
cnicutar Avatar answered Oct 02 '22 10:10

cnicutar