您的位置:首页 > 编程语言 > C语言/C++

结构体指针(关于C语言传值的理解)

2014-03-24 23:19 471 查看
//定义一个结构体
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->结构成员
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息