Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing memory addresses

How would i compare two memory addresses from a fixed sized char array? Lets say i have two pointers, each pointing to a different memory location in the array:

char *ptr1; //points to a memory address in the array;
char *ptr2; //points to another memory address in the array;

If i do printf("%p\n%p\n", ptr1, ptr2); then it will print the memory addresses as hexadecimal.

output:
0x601240
0x601274

how would i store these into variables and are they comparable so that i can tell which memory address comes first in the array.

Another question: Instead of %p if i do %d to print the memory address i get:

output:
6296128
6296180

are these valid memory addresses as well(i mean is this safe to use)?

like image 481
user2644819 Avatar asked Dec 09 '13 08:12

user2644819


1 Answers

The hexadecimal values are just representation of the address in the pointers. To compare two pointers(that point to elements of the same array or one past the end of the array), you can use code like

if (ptr1 < ptr2)

As for the format specifier, %d is not for pointers(though in some implementations, it prints the correct value, you shouldn't use it), use %p for void * pointers:

printf("%p\n%p\n", (void *)ptr1, (void *)ptr2);
like image 95
Yu Hao Avatar answered Oct 07 '22 07:10

Yu Hao