Article Directory
C language struct definition
1 Structure statement
struct Book
{
char name[100]; //书名
float price; //价格
}b1,b2; //全局变量
struct Book b3; //全局变量
//上面两种表示方式是相同的意思
int main()
{
struct Book b5; //做局部变量
return 0;
}
- Do anonymous structure type
struct
{
int a;
char b;
float c;
//此处未完全声明变量,缺少了结构体标签
}b;
struct
{
int a;
char b;
float c;
}*ps;//结构体的指针变量,用来存储地址
- ps = & x;
This way of writing is illegal, the compiler thinks these two different ways of writing are two different types.
2. Self-reference of structure
struct Node
{
int data;
struct Node*next;
};
int main()
{
struct Node a = { 3, NULL };
struct Node b = { 5, &a };
printf("%d\n", b.data);
printf("%p\n", b.next);
system("pause");
return 0;
}
- The following address is the address pointed to by b in the structure, namely the address of a.
- When the structure is self-referencing, it cannot be written as an anonymous structure type.
typedef struct
{
int data;
Node* next;
}Node;
-
The compilation error here is because Node is defined at the end, but it has been called inside the structure, which is illegal.
-
The correct wording is as follows:
typedef struct Node
{
int data;
struct Node* next;
}Node;
3. Definition and initialization of structure variables Initialization of simple structures
struct Point
{
int x;
int y;
};
int main()
{
struct Point p2 = { 1, 2 }; //定义一个局部变量p2并且给其进行赋值
printf("%d %d\n", p2.x, p2.y);
system("pause");
return 0;
}
- Initialization of structure nesting
struct Point
{
int x;
int y;
};
struct Node
{
int data;
struct Point p;
struct Node* next;
};
int main()
{
struct Node n1 = { 5, { 1, 2 }, NULL };
struct Node n2 = { 8, { 3, 4 }, &n1 };
printf("%d\n", n2.next->data);
printf("%d %d\n", n2.next->p.x, n2.next->p.y);
printf("%p\n", n2.next);
system("pause");
return 0;
}