gpt4 book ai didi

c - 访问和存储结构元素

转载 作者:行者123 更新时间:2023-11-30 18:26:40 28 4
gpt4 key购买 nike

我是编码新手,在一次事件中遇到了这段代码,这段代码到底是做什么的?提前致谢。

 #include <stdio.h>
#define OFFSETOF(TYPE,ELEMENT) ((size_t)&(((TYPE *)50)->ELEMENT))
typedef struct PodTag
{
char i;
int d;
int c;
} PodType;
int main()
{
printf("%d\n", OFFSETOF(PodType,c) );
printf("%d\n", OFFSETOF(PodType,d) );
printf("%d\n", OFFSETOF(PodType,i) );
printf("%d \n %d",(&((PodType*)0)->d),sizeof(((PodType*)0)->i));
getchar();
return 0;
}

最佳答案

此代码演示了结构如何在 C 中存储在内存中。

这样写代码会更好:

#include <stdio.h>

#define OFFSETOF(TYPE,ELEMENT) ((size_t)&(((TYPE *)100)->ELEMENT))

typedef struct PodTag {
char c;
int i;
int j;
} PodType;

int main()
{
printf("The size of a char is %d\n", sizeof(((PodType*)0)->c));
printf("The size of an int is %d\n", sizeof(((PodType*)0)->i));
printf("The size of a PodType is %d\n", sizeof(PodType));
printf("The size of a pointer to a PodType is %d\n\n", sizeof(PodType*));

printf("If there was a PodType at location 100, then:\n");
printf(" the memory location of char c would be: %d\n",
OFFSETOF(PodType,c));
printf(" the memory location of int i would be: %d\n",
OFFSETOF(PodType,i));
printf(" the memory location of int j would be: %d\n",
OFFSETOF(PodType,j));

return 0;
}

这段代码的输出是:

The size of a char is 1
The size of an int is 4
The size of a PodType is 12
The size of a pointer to a PodType is 8

If there was a PodType at location 100, then:
the memory location of char c would be: 100
the memory location of int i would be: 104
the memory location of int j would be: 108

关于c - 访问和存储结构元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277142/

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