Issue
I'm trying to learn how to use the pointer in a C program; my example is as follows:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int * tab = (int*)malloc(sizeof(int)*5);
int a = 10;
int *p;
p = &a;
printf("the address of a is %d \n",&a);
printf("the address of a using the pointer is %p \n",p);
printf("the address of tab is %d \n",tab);
}
I'm trying to print the address of a
, the address value inside of p
and where the first byte of the tab
begins.
I can get hexadecimal values when using "%p"
, but I'm willing the decimal value of the addresses.
Edit : On this Video image, someone has used "%d"
to print a decimal value for a pointer address, and it has confused me.
Solution
To print a decimal version of an object pointer, 1st convert the pointer to an integer. Best to use the optional type uintptr_t
.
The following type (
uintptr_t
) designates an unsigned integer type with the property that any valid pointer to void can be converted to this type (uintptr_t
) ... C11dr §7.20.1.4 1
#include <inttypes.h>
uintptr_t d = (uintptr_t)(void *) &a;
Then print it.
Some info on PRIuPTR
printf("%" PRIuPTR "\n", d);
For pre-C99 code, consider a direct cast to unsigned long
. @Barmar
OP later commented
"... i will try to manipulate the tab variable , and i will test if every cell in the tab is 4 byte , so may be i will do tab+8 bytes to get the value of a specific cell , here it's a simple example , with decimal it will be easy for me ."
This is a questionable approach as the decimalization of a pointer may not provide the continuous numeric model expected. This post this may be good for learning, but with OP providing more details in another post, even better ideas could be given for the higher level problem.
Answered By - chux - Reinstate Monica Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.