-1

我正在学习 C 语言并尝试学习一些有关 Structs 的知识,我在下面有这个示例,我试图了解结构内存分配是如何组成的。我了解到结构中的每个字段都是字长的,因此如果没有使用足够的内存,将会有空的内存空间,这应该在示例中看到,但是编译器给了我几个错误,例如Type specifier missingExpected 'Type名称需要说明符或限定符。怎么来的?

#include <stddef.h>
#include <stdio.h>

typedef struct
{
    char name[25];
    int id;
    int year;
    char material;
} Student;

int
main(void)
{
    Student talu;
    printf("Size of tAlu %d\n", (int)sizeof(talu));
    printf("name size is %d\n", offsetof(talu, name));
    printf("id size is %d\n", offsetof(talu, id));
    printf("year size is %d\n", offsetof(talu, year));
    printf("material size is %d\n", offsetof(talu, material));
    return 0;
}
4

5 回答 5

3

这是因为您忘记了右括号:

char name[25];
//         ^^^   !
于 2012-11-23T20:00:12.607 回答
3

你错过了一个括号。

 char name[25;

应该是 char name[25];

于 2012-11-23T20:00:31.197 回答
1

我也尝试编译你的代码并得到错误,所以我最终修复它是这样的:

#include <stddef.h>
#include <stdio.h>

typedef struct
{
    char name[25];
    int id;
    int year;
    char material;
} Student;

int
main(void)
{
    printf("Size of tAlu %d\n", (int)sizeof(Student));
    printf("name size is %d\n", offsetof(Student, name));
    printf("id size is %d\n", offsetof(Student, id));
    printf("year size is %d\n", offsetof(Student, year));
    printf("material size is %d\n", offsetof(Student, material));
    return 0;
}

这是使用 GCC 作为编译器。

于 2012-11-23T20:08:13.590 回答
0

OFFSETOF(3):“宏 offsetof() 返回字段成员从结构类型开始的偏移量。”

未报告字段的大小,但未报告它们在结构中放置的位置,offsetof()之所以使用是因为:

“组成结构的字段的大小可能因实现而异,编译器可能会在字段之间插入不同数量的填充字节”。

于 2012-11-23T20:25:11.080 回答
0

offsetof()取成员偏移量的类型作为第一个参数计算。

阅读手册页会有所帮助。

于 2012-11-23T20:13:10.743 回答