![](/img/trans.png)
[英]Z-wave protocol with C: Questions about Z-wave frame structure & programming in general
[英]Questions about Structure definitions
我是c的新手,我有一個關於結構的問題(見下一個代碼):
typedef struct student{
char name[20];
int grade;
} student1;
typedef struct group_project{
char name_of_group[20];
struct group_project *next; // points to the next group
student1 *student1; //head of the group
} group_project;
student1
是類型struct student
的別名。
在group_project
結構中,類型別名group_project
尚不存在,因此您必須使用struct group_project
。
在 C 中,您不能在沒有關鍵字struct
的情況下使用結構標記名稱(例如student
)。 整個類型是struct student
。
student
和student1
之間有什么區別(結構的名稱是什么?)。 可以用同一個名字嗎?
student
是結構標記或結構本身的“名稱”,而student1
是類型struct student
的typedef
d別名。 是的,它們可以具有相同的名稱或標識符,因為它們位於不同的名稱空間中。
為什么在使用 group_project 時需要添加“
struct
”,而在使用group_project
結構時student1
添加struct
?
在 C 中,與 C++ 不同,當您定義結構的 object 時,沒有對結構進行typedef
或在結構本身的聲明中定義 object,您必須在結構標記之前加上關鍵字struct
各自 object 的聲明,例如:
struct student student_x; // `struct` keyword required.
由於student1
之前已經是typedef
d,在結構student
的聲明中,當您定義該結構類型的 object 時,您不再需要使用struct
關鍵字。
與此相反, group_project
作為project_group
結構中next
指針的類型需要在關鍵字struct
之前,因為group_project
的typedef
在源代碼中隨后定義,並且此時在結構內部無效。
可以使用沒有“
typedef
”的結構嗎?
是的當然。 社區中的一些用戶甚至說這更受贊賞,因為它使您的代碼更具可讀性。 我建議始終單獨使用該結構而不是與任何typedef
混合,即使它需要更多的鍵輸入,只是為了讓您的代碼更清晰一點,但這是一個意見和風格的問題。 在這里你可以制作你自己的形象:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.