我目前正在学习 C 中的 struct
数据结构,以及如何使用 typedef
关键字作为此结构的前缀。这导致实际结构的变量名被放置在不同的命名空间中,如几个不同的引用文献中所述:
Difference between 'struct' and 'typedef struct' in C++?
typedef struct vs struct definitions
但是,不清楚我正在使用的示例发生了什么:
#include <stdio.h>
struct demo
{
short low_pass_vcf;
short filter_coupler;
short reverb;
short sequential;
} synth;
int main()
{
printf("Size of struct: %i\n", sizeof(struct demo));
printf("Size of struct: %i\n", sizeof(synth));
return 0;
}
在这个例子中,我可以通过synth
变量名访问struct
数据结构;但是,在我看到的示例中,为了能够执行此操作,struct
需要以 typedef
开头。在此示例中,未使用 typedef
,但我仍然可以通过 synth
引用此结构。我想知道 C 允许我这样做到底发生了什么?任何解释将不胜感激。干杯。
最佳答案
struct demo
{
short low_pass_vcf;
short filter_coupler;
short reverb;
short sequential;
} synth;
等同于:
// declare struct demo
struct demo
{
short low_pass_vcf;
short filter_coupler;
short reverb;
short sequential;
};
// define struct variable synth
struct demo synth;
现在您可以访问结构成员,例如:
synth.sequential = 1;
sizeof(struct demo)
返回 struct demo
的大小。
sizeof(synth)
返回具体实例 synth
的大小。
在这种情况下,两者都返回相同的尺寸。
更新:
使用 typedef
它可能看起来像这样:
// declare new type demo
typedef struct demo
{
short low_pass_vcf;
short filter_coupler;
short reverb;
short sequential;
} demo_t;
// define demo_t variable synth
demo_t synth;
更新 2:
Chapter 5: Typedefs
Please don't use things like "
vps_t
". It's a mistake to use typedef for structures and pointers. When you see avps_t a;
in the source, what does it mean? In contrast, if it says
struct virtual_container *a;
you can actually tell what "a" is.
关于c - 没有 typedef 关键字的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32656226/