結構體指針(關於C語言傳值的理解)

    //定義一個結構體
    struct word_count
    {
        int ch_count;
        int word_count;
        int line_count;
    };
    //定義一個結構體指針
    typedef struct word_count *p_count_struct;
    //對結構體進行初始化
    void init(p_count_struct *count_ent)
    {
        (*count_ent) = (struct word_count *)malloc(sizeof(struct word_count));
        (*count_ent)->ch_count = 0;
        (*count_ent)->word_count = 0;
        (*count_ent)->line_count = 0;
    //printf("ch_count: %d, word_count: %d, line_count: %d\n", (*count_ent)->ch_count, (*count_ent)->word_count, (*count_ent)->line_count);
    }
    //main函數調用
    int main(int argc, char *argv[])
    {
        p_count_struct count_ent;
        init(&count_ent);
        printf("ch_count: %d, word_count: %d, line_count: %d\n", count_ent->ch_count, count_ent->word_count, count_ent->line_count);
    }


  • 理解
    main函數將結構體指針的地址(&count_ent)傳遞給init函數,p_count_struct *爲結構體指針的指針類型,所以現在init函數中的count_ent是一個結構體指針的地址(不同與main函數中的count_ent),對其解引用*count_ent纔是結構體指針。另外:當一個指針p指向一個結構體時,可以用p->結構成員

發佈了37 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章