结构基本功能
结构声明由包含在花括号内的一系列声明组成,结构中定义的变量称为成员。
#include <stdio.h>
struct point
{
int x;
int y;
};
int main(int argc, char const *argv[])
{
return 0;
}
如果结构声明的后面不带变量名,则不需要为它分配存储空间,它仅仅描述了一个结构的模板或轮廓。如果结构声明后面带变量名,则可以通过该变量名直接使用结构功能。
#include <stdio.h>
struct point
{
int x;
int y;
} p1, p2;
int main(int argc, char const *argv[])
{
p1.x = 233;
p1.y = 666;
printf("x = %d, y = %d.\n", p1.x, p1.y);
p2.x = 100;
p2.y = 200;
printf("x = %d, y = %d.\n", p2.x, p2.y);
struct point p3;
p3.x = 200;
p3.y = 100;
printf("x = %d, y = %d.\n", p3.x, p3.y);
struct point p4 = {666, 233};
printf("x = %d, y = %d.\n", p4.x, p4.y);
return 0;
}
结构可以嵌套。
#include <stdio.h>
struct point
{
int x;
int y;
};
struct info
{
int width;
int height;
};
struct rect
{
struct point point;
struct info info;
};
int main(int argc, char const *argv[])
{
struct rect rect;
rect.point.x = 100;
rect.point.y = 100;
rect.info.width = 300;
rect.info.height = 200;
printf("x: %d, y: %d.\n", rect.point.x, rect.point.y);
printf("width: %d, height: %d.\n", rect.info.width, rect.info.height);
return 0;
}