I am writing a code to read the address of the node in linked list so can some one confirm if %p and %u format in printf is correct. One gives me the hex and other gives me a decimal and conversion to hex or deci are matching. Also it will be great if someone can brief on difference of %p and %u.
struct node {
int x;
struct node *next;
};
int main () {
struct node *root;
struct node *track;
root = malloc(sizeof(struct node));
printf ("Location of root is %p\n", root);
printf ("Location of root is %u\n", root);
}
Output of execution:
[root@vm c_prog]# ./a.out Location of root is 0xdc3010 Location of root is 14430224 [root@vm c_prog]# ./a.out Location of root is 0x11fbf010 Location of root is 301723664 [root@vm c_prog]# ./a.out Location of root is 0x7e8e010 Location of root is 132702224 [root@vm c_prog]#
%pis for a pointer, and is correct. Strictly speaking, you should cast tovoid *, but I’ve never met an implementation that cared. Example:%uis for anunsigned intand is not correct, unless you play some casting gymnastics and are sure a pointer and anintare the same size. To safely print a pointer value in decimal, you should usePRIuPTRfrominttypes.h: