■ソースコード
#include <stdio.h>
#include <string.h>
// 文字列処理に string.h が必要
struct person{ // 個人データ
char name[40]; // 名前
struct person *next;
}; // セミコロン「;」が必要
/* リストを表示する関数 */
void print(struct person list){
struct person *pointer;
int count =1;
pointer = &list;
// NULL は「セットされていない」の意味
while(pointer!=NULL){
printf("%d 名前=%s\n",count,pointer->name);
pointer=pointer->next;// 次のポインタ
count++;
}
}
int main(void){
struct person p1,p2,p3,p4;
// データ初期化
strcpy(p1.name,"鈴木一郎");
strcpy(p2.name,"福留孝介");
strcpy(p3.name,"松井秀喜");
strcpy(p4.name,"岩村明憲");
// ポインタをセット
p1.next = &p2; // 鈴木の次は福留
p2.next = &p3; // 福留の次は松井
p3.next = NULL; // 松井の次は定義しない
print(p1);
printf("...順番入れ替えと追加\n");
p3.next = &p2;
p2.next = &p4;
p4.next = &p1;
p1.next = NULL;
print(p3);
}
■実行結果
>hellostructlist.exe
1 名前=鈴木一郎
2 名前=福留孝介
3 名前=松井秀喜
...順番入れ替えと追加
1 名前=松井秀喜
2 名前=福留孝介
3 名前=岩村明憲
4 名前=鈴木一郎