Reputation: 39
I'm trying to print the address a pointer is holding in C. Would I use %d or %p for the format specifier? And are all pointer addresses ints? In this youtube video, I thought that was the case but when I tried to code something, it would not compile unless I used %p. Also, isn't i_ptr+1 supposed to be the memory address i_ptr holds + 4 because an int is 4 bytes? https://www.youtube.com/watch?v=JTttg85xsbo
Thankyou!!!!
#include <stdio.h>
void test(int *i_ptr);
int main() {
int i[5];
test(i);
return 0;
}
void test(int *i_ptr) {
printf("%d\n", i_ptr);
printf("%d\n", i_ptr + 1);
}
~
Upvotes: 0
Views: 102
Reputation: 206717
If you have a compiler that supports C99, you can use the type uintptr_t
to hold the value of a pointer. However, since its size is not specified by compiler and there isn't a printf
specifier for such a type, you have to experiment with using "%d"
, "%ld"
and "%lld"
to make things work. I want to emphasize that it is not portable code.
The following code worked for me, using gcc 4.8.2 on a 64-bit Linux machine with -std=c99
.
#include <stdio.h>
#include <stdint.h>
void test(int *i_ptr);
int main() {
int i[5];
test(i);
return 0;
}
void test(int *i_ptr) {
uintptr_t p = (uintptr_t)i_ptr;
printf("%ld\n", p);
p = (uintptr_t)(i_ptr+1);
printf("%ld\n", p);
}
With the following output from a sample run.
140735074589984
140735074589988
Update
The format specifier "%td"
is meant to be used for ptrdiff_t
. It's more likely that it will work for uintptr_t
as well.
Upvotes: 1