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)?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With