user3995169
user3995169

Reputation: 145

How is the comparison b/w pointers & integers

I want to print all the addresses are the same if the particular addresses in a two dimensional arrays are the same. Looking at error:

comparison between pointer and integer [enabled by default]

One thing I have understood is I can't compare addresses. It would give me a compilation error. But isn't there any method of doing that. How should my program check that all address are same and then it should print out the statement.

/* Address and  pointers*/ 

#include <stdio.h>

main()
{
  int a[10][20]; 

  a[1][1]=3;

  printf("%p %p %p %p", a[1], a+1, &a[1] , &a[1][0]); 

  if( a[1]== a+1== &a[1] == &a[1][0])
     printf("\nAll are same address\n"); 
}

Upvotes: 1

Views: 94

Answers (1)

M.M
M.M

Reputation: 141648

Using %p with something that's not void * causes undefined behaviour. Often we can gloss over that point, but it's actually relevant here, so that line should be:

printf("%p %p %p %p", (void *)a[1], (void *)(a+1), (void *)&a[1] , (void *)&a[1][0]); 

Moving onto a[1]== a+1== &a[1] == &a[1][0]. I'm sure you recall that == is a binary operator (i.e. takes exactly two arguments), which evaluates to either 0 or 1, and is left-associative. So this expression is:

((a[1] == a+1)== &a[1]) == &a[1][0]

Now, a[1] == a+1 is 1 since those are alternative syntax for the same thing. So now we move onto evaluating 1 == &a[1]. Since 1 is an int and &a[1] is a pointer, this comparison is ill-formed.

In general, if your intent is to check that four items are all equal you need to write if ( A == B && A == C && A == D ) or equivalent.

However, if ( a[1] == &a[1] ) is also a constraint violation. To compare two pointers, it only works if they are both the same type (implicit conversions may be done here). However there is no implicit conversion from int * to int (*)[3] or vice versa. To attempt this comparison you must cast at least one of the operands. One option is to cast both to void * as this is always legal and it must point to the first byte of whatever the operand was pointing to:

if ( (void *)a[1] == (void *)&a[1] )

So to summarize, your code could better be written as:

void *p = a[1];
void *q = a + 1;
void *r = &a[1];
void *s = &a[1][0];

printf("%p %p %p %p\n", p, q, r, s);

if ( p == q && p == r && p == s )
    printf("All are same address\n");

Upvotes: 5

Related Questions