什么是结构? 结构是在C/C++中创建用户定义的数据类型的关键字。结构创建的数据类型可用于将可能不同类型的项分组为单一类型。
如何创建结构? “struct”关键字用于创建结构。下面是一个例子。
C
struct address { char name[50]; char street[100]; char city[50]; char state[20]; int pin; }; |
如何声明结构变量? 结构变量既可以用结构声明声明,也可以像基本类型一样作为单独的声明声明。
C
// A variable declaration with structure declaration. struct Point { int x, y; } p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data types struct Point { int x, y; }; int main() { struct Point p1; // The variable p1 is declared like a normal variable } |
注意:在C++中,结构变量在声明变量之前是可选的。在C语言中,它是强制性的。
如何初始化结构成员? 结构件 不可能 用声明初始化。例如,下面的C程序编译失败。
C
struct Point { int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here }; |
上述错误的原因很简单,当声明数据类型时,没有为其分配内存。只有在创建变量时才会分配内存。 结构件 可以是 使用大括号“{}”初始化。例如,下面是一个有效的初始化。
C
struct Point { int x, y; }; int main() { // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = {0, 1}; } |
如何访问结构元素? 使用点(.)访问结构构件操作人员
C
#include<stdio.h> struct Point { int x, y; }; int main() { struct Point p1 = {0, 1}; // Accessing members of point p1 p1.x = 20; printf ("x = %d, y = %d", p1.x, p1.y); return 0; } |
x = 20, y = 1
什么是指定的初始化? 指定的初始化允许以任何顺序初始化结构成员。此功能已添加到 C99标准 .
C
#include<stdio.h> struct Point { int x, y, z; }; int main() { // Examples of initialization using designated initialization struct Point p1 = {.y = 0, .z = 1, .x = 2}; struct Point p2 = {.x = 20}; printf ("x = %d, y = %d, z = %d", p1.x, p1.y, p1.z); printf ("x = %d", p2.x); return 0; } |
x = 2, y = 0, z = 1x = 20
此功能在C++中不可用,只在C中工作。 什么是结构阵列? 与其他基本数据类型一样,我们可以创建一个结构数组。
C
#include<stdio.h> struct Point { int x, y; }; int main() { // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; printf ("%d %d", arr[0].x, arr[0].y); return 0; } |
10 20
什么是结构指针? 和基元类型一样,我们可以有指向结构的指针。如果我们有一个指向结构的指针,则可以使用箭头(->)操作符访问成员。
C
#include<stdio.h> struct Point { int x, y; }; int main() { struct Point p1 = {1, 2}; // p2 is a pointer to structure p1 struct Point *p2 = &p1; // Accessing structure members using structure pointer printf ("%d %d", p2->x, p2->y); return 0; } |
1 2
什么是结构件对齐? 看见 https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/ C结构的局限性 在C语言中,结构提供了一种将不同类型的数据打包在一起的方法。结构是处理一组逻辑相关数据项的有用工具。然而,C结构有一些局限性。
- C结构不允许将结构数据类型视为内置数据类型:
- 我们不能在结构变量上使用+、-等运算符。例如,考虑下面的代码:
C
struct number { float x; }; int main() { struct number n1,n2,n3; n1.x=4; n2.x=3; n3=n1+n2; return 0; } /*Output: prog.c: In function 'main': prog.c:10:7: error: invalid operands to binary + (have 'struct number' and 'struct number') n3=n1+n2; */ |
- 无数据隐藏: C结构不允许数据隐藏。结构成员可以由结构范围内的任何函数访问。
- 结构内部的功能: C结构不允许结构内部的功能
- 静态成员: C结构体内不能有静态构件
- 访问修饰符: C编程语言不支持访问修饰符。所以它们不能用在C结构中。
- 结构中的建筑创作: C中的结构不能在结构中包含构造函数。
相关文章: C结构与C++结构