Ömer Kazım Zora
Ömer Kazım Zora

Reputation: 25

compare "int* pointer" with constant memory address

How can I compare a pointer value with a constant memory address?

#define ADR 0x2000
unsigned int * po;
if(po<ADR) { };

Above code works but it gives a warning "comparison between pointer and integer"

Upvotes: 1

Views: 1251

Answers (2)

mjs
mjs

Reputation: 3004

The issue is that you are actually doing this:

unsigned int * p;
if(p<0x2000) {};

Where 0x2000 is an integer. You can resolve this by using a cast:

#define ADR 0x2000
unsigned int * p;
if(p<(unsigned int*)ADR) {};

Although a better option might be to actually add the cast into the #define like so:

#define ADR ((unsigned int*) 0x2000)

As @Alter Mann (cryptically) points out, technically you should actually cast the pointer to an integer. See this answer for details.

Upvotes: 1

vlad_tepesch
vlad_tepesch

Reputation: 6925

make the define to be of type 'pointer'.

#define ADR ((unsigned int*) 0x2000)
unsigned int * po;
if(po<ADR) { };

Also i highly recommend using stdint.h types for such definitions. just in case the compiler and hardware has a different understanding to you of how large an int is.

Also use the correct attributes. defining fix addresses often implies some kind of memory mapped io. then you have to use the volatile to tell the compiler that the content of that address may change surprisingly.

If its an read only address use a const qualifier.

#include <stdint.h>

#define ADR ((volatile uint16_t*) 0x2000)
uint16_t * po;
if(po<ADR) { };

Upvotes: 1

Related Questions