C 語言初學教材 - 第六章 雙重指標 範例程式

雙重指標範例程式碼



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define NAME_SIZE 15
 
// 記錄好友資料的結構
struct friendData {
    char name[NAME_SIZE];
    int age;
    int sex;
    int relation;
};
 
// 暫存在記憶體中的資料結構:鏈結串列
struct linkedListNode {
    struct friendData data;
    struct linkedListNode *nextPtr;
};
 
typedef struct linkedListNode LinkedListNode;
 
void addfriend(LinkedListNode **startPtr);
void printList2(LinkedListNode *currentPtr);
 
int main(void)
{
    LinkedListNode *startPtr;
    int i;
     
    i = 0;
    startPtr = NULL;
    while (i < 5) {
        addfriend(&startPtr);
        i++;
    }
    printList(startPtr);
     
    return 0;
}
 
void addfriend(LinkedListNode **startPtr)
{
    LinkedListNode *newPtr, *currentPtr;
    char fname[NAME_SIZE];
    int fage, fsex, frelation;
 
    // 向作業系統要求新的記憶體空間
    newPtr = malloc(sizeof(LinkedListNode));
         
    // 依序輸入好友資料
    printf("\n好友暱稱: ");
    scanf("%s", fname);
    printf("好友年齡: ");
    scanf("%d", &fage);
    printf("好友性別 - 0.女 1.男: ");
    scanf("%d", &fsex);
    printf("好友關係 - 0.家人 1.同學 2.朋友: ");
    scanf("%d", &frelation);
         
    // 將好友資料拷貝到剛才取得的記憶體空間之中
    strcpy(newPtr->data.name, fname);
    newPtr->data.age = fage;
    newPtr->data.sex = fsex;
    newPtr->data.relation = frelation;
    newPtr->nextPtr = NULL;
         
    // 將資料加入鏈結串列
    if (*startPtr == NULL) {
        *startPtr = newPtr;
    }
    else {
        currentPtr = *startPtr;
            
        while (currentPtr != NULL) {
           if (currentPtr->nextPtr == NULL) {
               currentPtr->nextPtr = newPtr;
               break;
           }
                        
           currentPtr = currentPtr->nextPtr;
        }
    }
}
 
void printList2(LinkedListNode *currentPtr)
{
    if (currentPtr == NULL) {
        printf("\n\n還沒有建立任何好友資料唷...\n\n");
    }
    else {
        // 依序由鏈結串獵取出資料,然後印在螢幕上
        printf("\n\n以下依好友名錄的儲存順序印出好友資料\n");
        printf("  好友暱稱 - 年 齡 - 性 別 - 關 係\n");
        while (currentPtr != NULL) {
            printf("%10s - ", currentPtr->data.name);
            printf("%5d - ", currentPtr->data.age);
            printf("%5s  - ", currentPtr->data.sex ? "男" : "女");
            printf("%s \n", currentPtr->data.relation ? "同學或朋友" : "家人");
         
            currentPtr = currentPtr->nextPtr;
        }
    }
         
}
 
/* 《程式語言教學誌》的範例程式
    檔名:listtestr.c
    功能:示範鏈結串列的使用 
    作者:張凱慶
    時間:西元2010年7月 */


程式說明及編譯執行,請參考




沒有留言: