在 typedef 的名称前加上 *
Preceding the name of a typedef with *
我最近发现在 C 中定义 typedef 结构时可以在变量前面加上 *。
这是我所说的一个例子(*book
就是这种情况):
typedef struct item {
int id;
float price;
} *book, pencil;
我不太明白这是怎么回事。
这 3 个变量在数据类型方面是否相同?
struct item *foo;
book bar;
pencil *foobar;
都具有相同的类型 = 指向 struct item
的指针。
book type IMO 很危险,因为它将指针隐藏在 typedef 中,使代码的可读性降低(对人类而言)且容易出错
来看个例子
#include <stdio.h>
typedef char *ptr1; //This all are same
typedef char * ptr2;
typedef char* ptr3;
int main()
{
printf("%zu\n",sizeof(ptr1));
printf("%zu\n",sizeof(ptr2));
printf("%zu\n",sizeof(ptr3));
return 0;
}
输出:
8
8
8
在 64 位机器中见 Demo
输出为 8,因为它是 x86-x64 中指针的大小(在 32 位中为 4)
你的情况
#include <stdio.h>
typedef struct item
{
int id;
// float price; // I comment this line for clarity
}*book, pencil;
int main()
{
printf("%zu\n",sizeof(book));
printf("%zu\n",sizeof(pencil));
return 0;
}
输出:
8
4
见Demo
谢谢。
我最近发现在 C 中定义 typedef 结构时可以在变量前面加上 *。
这是我所说的一个例子(*book
就是这种情况):
typedef struct item {
int id;
float price;
} *book, pencil;
我不太明白这是怎么回事。
这 3 个变量在数据类型方面是否相同?
struct item *foo;
book bar;
pencil *foobar;
都具有相同的类型 = 指向 struct item
的指针。
book type IMO 很危险,因为它将指针隐藏在 typedef 中,使代码的可读性降低(对人类而言)且容易出错
来看个例子
#include <stdio.h>
typedef char *ptr1; //This all are same
typedef char * ptr2;
typedef char* ptr3;
int main()
{
printf("%zu\n",sizeof(ptr1));
printf("%zu\n",sizeof(ptr2));
printf("%zu\n",sizeof(ptr3));
return 0;
}
输出:
8
8
8
在 64 位机器中见 Demo
输出为 8,因为它是 x86-x64 中指针的大小(在 32 位中为 4)
你的情况
#include <stdio.h>
typedef struct item
{
int id;
// float price; // I comment this line for clarity
}*book, pencil;
int main()
{
printf("%zu\n",sizeof(book));
printf("%zu\n",sizeof(pencil));
return 0;
}
输出:
8
4
见Demo
谢谢。