C结构中成员的地址

Address of a member in C structure

我有下面的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{

typedef struct {
    float x;
    float y;
    int *t;
    }C;


C *z;

z=(C*)malloc(sizeof(C));

z->x=4;
z->y=6;
z->t=(int*)malloc(sizeof(int));
*(z->t) =10;
// Access value
printf("%d\n",*(z->t));

// Access address
printf("%d\n",z->t);

// Access value
printf("%f",z->x);

// Access address of z->x ?


free(z);

}

在代码中我可以访问 int *t 的地址和值但是对于 float x 我只知道如何使用 z->x 访问值,我如何访问 z->x 的地址?

使用 &(地址)运算符

float *address = &(z->x); // maybe parenthesis are redundant
printf("addres of z->x is %p\n", (void*)address);

您需要使用 & 运算符。此外,要打印地址,您必须使用 %p 格式说明符和 printf()

值得一提1%p 需要 void * 类型的参数。由于 void * WRT float * 的表示可能存在一些差异,因此最好将参数转换为 void *.

所以,总的来说,

printf("%p",(void *)&(z->x));

会给你z.

中的成员变量x的地址

1 : 感谢pmg先生的评论