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;
}
返回“學點C語言 - 目錄”