top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Pointer arithmetic issue in C/C++?

+1 vote
475 views
int main()
{
    int *x;
    int *y;
    x * y;
    x - y;
    x + y;
}

In the above program we see the error at x*y and x+y not on the x-y. Please explain?

posted Jul 28, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
1. Addition of two pointers is invalid.
2. Multiplication of two pointers/one pointer and one variable(int/float etc) is also invalid.

2 Answers

+1 vote

Addition,divide and multiplication of 2 pointer is invalid because they are the representing memory address. So logically also it is invalid.
But the subtraction of two pointer is valid. show the difference of two memory locations.

answer Jul 28, 2014 by Double S
0 votes

I believe your query is why it is kept in these way -

Addition or multiplication of two pointers generates a very bug number (pointer) which most likely may be out of the function space so it is kept invalid. While this is not true in case of subtraction and it tell the distance between two pointers which is a meaningful information (not true with division).

answer Jul 29, 2014 by Salil Agrawal
Similar Questions
+3 votes
#include<stdio.h>
#include<conio.h>
#define PROD(x) (x*x)
void main()
{
 clrscr();
 int p=3,k;
 k=PROD(p+1); //here i think value 3+1=4 would be passed to macro
 printf("\n%d",k);
 getch();
}

In my opinion, the output should be 16, but I get 7. Can anyone please help me why?

+1 vote

int arr[ ] = { 1, 2 };
p = arr; /* p is pointing to arr */

How pointer p will behave ?

...