理解指向结构的指针是指c中的指针成员访问它

时间:2017-05-17 04:02:55

标签: c pointers struct

我有一个以下程序并且编译成功但是在运行时,程序在eclipse中崩溃

struct Student
{
   unsigned int  *ptr;  //Stores address of integer Variable
}*s1;

int main()
{
    unsigned int roll = 20;
    s1->ptr   = &roll;

    printf("\nRoll Number of Student : %d",*(s1->ptr));

    return(0);
}

如何使用指向结构的指针打印roll的值

1 个答案:

答案 0 :(得分:2)

创建Student结构,分配并使用它

typedef struct Student
{
   unsigned int  *ptr;  //Stores address of integer Variable
} Student;

int main()
{
    Student *s1;
    unsigned int roll = 20;
    s1 = malloc(sizeof(Student));
    if (s1 == NULL) {
        return -1;
    }
    s1->ptr   = &roll;

    printf("\nRoll Number of Student : %d",*(s1->ptr));
    free(s1);

    return(0);
}