Suppose I have a pointer-to-structure Y, and that structure contains a structure variable (not a pointer) X.
What will be the correct way to print the address of X, so that I can use the address to fetch more info on X?
printf("address is %x", Y->X)
Or
printf("address is %x", &(Y->X))
CodePudding user response:
Y is a pointer to a structure.
Y->X is the member X of the structure. If X is itself a structure, Y->X is still the member X, so it is a structure. It is not a pointer or address.
The address of Y->X is &Y->X. If you want to print or use the address of Y->X, use &Y->X.
To print a pointer, convert it to void * and format it with %p:
printf("The address of Y->X is %p.\n", (void *) &Y->X);
The %p conversion specifier uses an implementation-defined format for addresses. If you want more control over formatting of an address, you can include <inttypes.h> and <stdint.h>, convert the pointer to uintptr_t, and use formatting macros from <inttypes.h>. For example, to format it as a hexadecimal numeral with at least 16 digits (using leading zeros as necessary), use:
printf("The address of Y->X is 6" PRIxPTR ".\n", (uintptr_t) &x);
CodePudding user response:
This sample should give you answer and understand some stuff.
#include <stdio.h>
struct Y {
int x;
};
int main() {
struct Y yobj;
struct Y *ptr;
yobj.x=101;
ptr = &yobj;
int *ptr2 = &(ptr->x);
printf ("\n the address of x :%p", &(ptr->x));
printf ("\n the value of x :%d", *ptr2);
return 0;
}
CodePudding user response:
the second form is the correct one. The first evaluates to the structure itself. Some modern compiler should yield an error because format %x expects an adress not a structure.
