1. 包含数组的结构:
#include <stdio.h>
int main(void)
{
struct Rec {
int x[3];
int y;
} r1;
r1.x[0] = 11; r1.x[1] = 22; r1.x[2] = 33;
r1.y = 99;
printf("%d,%d,%d,%d", r1.x[0], r1.x[1], r1.x[2], r1.y);
getchar();
return 0;
}
2. 结构中的结构:
#include <stdio.h>
int main(void)
{
struct Rec1 {
int x,y,z;
};
struct Rec2 {
int ID;
struct Rec1 num;
} R;
R.ID = 9;
R.num.x = 1;
R.num.y = 2;
R.num.z = 3;
printf("%d,%d,%d,%d", R.ID, R.num.x, R.num.y, R.num.z);
getchar();
return 0;
}
#include <stdio.h>
int main(void)
{
struct Rec {
int ID;
struct {
int x;
int y;
int z;
} num;
} R;
R.ID = 9;
R.num.x = 1;
R.num.y = 2;
R.num.z = 3;
printf("%d,%d,%d,%d", R.ID, R.num.x, R.num.y, R.num.z);
getchar();
return 0;
}
3. 链表(结构中的指针):
#include <stdio.h>
int main(void)
{
struct Rec {
int x;
int y;
struct Rec *next; /* 结构中的指针, 这是建立链表的基础 */
} *p=NULL, *pFirst=NULL, *pPrec=NULL;
/* 建立链表 */
int i;
for (i = 0; i < 10; i++) {
p = (struct Rec *)malloc(sizeof(struct Rec));
p->x = i;
p->y = i*i;
p->next = NULL;
if (!pFirst) {
pFirst = p;
pPrec = p;
} else {
pPrec->next = p;
pPrec = p;
}
}
/* 遍历链表 */
p = pFirst;
while (p) {
printf("%d, %d\n", p->x, p->y);
p = p->next;
}
/* 释放链表 */
p = pFirst;
while (p) {
pPrec = p;
p = p->next;
free(pPrec);
}
getchar();
return 0;
}