Is it possible to compare a pointer and an integer in C?

I am writing code that maps virtual addresses to physical addresses.

I have the code in these lines:

if (address > 0xFFFF)
   Status = XST_FAILURE; // Out of range
else if (address <= 0xCFFF || address >= 0xD400) {
   // Write to OCM
   Xil_Out8(OCM_HIGH64_BASEADDR + OCM_OFFSET + address, data);
else { // (address >= 0xD000)
   // Write to external CCA
   Status = ext_mem_write(address, data);

I get a compiler warning: comparison between pointer and integer [enabled by default]

I understand that I am comparing two different types (pointer and integer), but is this a problem? After all, comparing a pointer to an integer is exactly what I want to do.

Would it be easier to define pointer constants for comparison instead of integers?

const int *UPPER_LIMIT = 0xFFFF;
...
if (address > UPPER_LIMIT ){
    ....
+4
source share
3 answers

A clean way is to use constants of the type uintptr_t, which is defined as an unsigned integer that can unambiguously display between pointers and integers.

#include <stdint.h>. , , C, .

"" , . , , , , - .

:

uintptr_t foo = 0xFFFF;

void test(char *ptr)
{
    if ( (uintptr_t)ptr < foo )
         // do something...
}

C. , void * uintptr_t, - undefined, , , .

+3

, Linux Kernel unsigned long ( , , - , ).

:

  • C , int ( ) 0xFFFF address - . 6.5.8.
  • , - . - , 6.3.2.3. , :
    • 0xFFFF, , int - . 6.4.4, int, sizeof(int) < sizeof(void*), .
    • , 0xFFFF , 0xFFFFFFFF ( , )

, (2) , . ( , - , , ), .

" ": GCC 4.8 UB (Undefined Behavior) , , : https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61569

N1570 - C11

+2

unsigned int, : (unsigned)address - 32 16- .

-1

All Articles