Click here to Skip to main content
15,890,350 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
XML
#include<stdio.h>
#include <string.h>
int main()
{
int *p1, *p2;
int ar[2];

p1=&ar[0];
p2=&ar[1];

printf( "%d\n",p2 - p1); // this is right

printf( "%d\n",p2 + p1); // why this is wrong

    return 0;
}
Posted

The first one is calculating an offset by taking the difference. This value can be used to increment an existing pointer by n values. It is basically the count of items between the two pointers.

E.g.
C++
p4 =  p3+(p2-p1);

is valid as it does increment p3 by the number of items between p2 and p1.

If you add on the other hand two pointers you are adding two addresses which will point to a memory location far far away in your allocated array and is definitely an error.
 
Share this answer
 
The C programming language specification forbids the addition of pointers, see, for instance: "ISO/IEC 9899:TC3" pag. 82[^].
 
Share this answer
 
The first one is correct is a coincidence probably. You must use as *p2 - *p1 and *p2 + *p1

If you write p1 it gets its address
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900