开发者社区 问答 正文

C语言结构体指针初始化问题。

#include "stdio.h"
#include "stdlib.h"

struct Student{
    int age;
};

void Init(struct Student* pStudent)
{
    pStudent = (struct Student*)malloc(sizeof(Student));
} 

int main()
{
    struct Student *pStudent;
    Init(pStudent);
    pStudent->age = 1;
    return 0;
}

这段代码会奔溃,我调试发现指针pStudent没有初始化成功。然后我在Init里面修改pStudent->age的值是没问题的,请大家指点一下

展开
收起
a123456678 2016-06-08 22:31:56 2338 分享 版权
1 条回答
写回答
取消 提交回答
  • #include "stdio.h"
    #include "stdlib.h"
    
    struct Student{
        int age;
    };
    
    struct Student* Init()
    {
        struct Student* pStudent = (struct Student*)malloc(sizeof(Student));
        return pStudent;
    } 
    
    int main()
    {
        struct Student *pStudent = Init();
        pStudent->age = 1;
        free(pStudent);
        return 0;
    }
    2019-07-17 19:32:51
    赞同 展开评论
问答分类:
问答地址: