gpt4 book ai didi

c - 结构和指针运算

转载 作者:太空宇宙 更新时间:2023-11-04 03:14:20 25 4
gpt4 key购买 nike

#include <stdio.h>

struct student
{
int roll_no;
int total_marks;
} s1;

int main()
{
struct student *stu;
stu = &s1;
printf("Address of member roll_no accessed by s1 = %u", &s1.roll_no);
printf("Address of member total_marks accessed by s1 = %u", &s1.total_marks);
printf("Value of stu = %u", stu); // which is address of s1.roll_no

同样,如何使用 stu 获取 s1.total_marks 的地址?

完全想通了。假设我们有这样的结构:这些成员中的每一个都可以通过以下方式访问,

   #include <stddef.h>   

struct student
{
int roll_no;
char name[50];
double mark;
double percetage;
};

int main()
{
struct student s = {1, "Jug", 98.99, 97.5678};

printf("%d %s\n", *(int*)((char*)&s + offsetof(struct student,
roll_no)), (char*)((char*)&s + offsetof(struct student, name)));
printf("%lf %lf", *(double*)((char*)&s + offsetof(struct student,
mark)), *(double*)((char*)&s + offsetof(struct student, percentage)));
}```

最佳答案

成员访问 运算符(.->)具有更高的 precedenceaddress-of 运算符 (&)。所以 &p->m 等同于 (&p)->m,而是 &(p->m)

因此,您可以使用

&stu->total_marks

以及你已经写过的

&s1.total_marks

关于c - 结构和指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53334923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com