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

标签 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 的值

最佳答案

创建一个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);
}

关于c - 理解指向结构的指针是指访问它时c中的指针成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44015332/

相关文章:

go - 从嵌入式结构遍历结构值

c - 为什么 str[5]、str[] = "1234"和 str = malloc(5) 有不同的大小?

c - 我无法弄清楚下面的代码如何产生 fffffffaa 的输出,请帮助我理解?

c - 编写一个函数,显示三个不同数字的所有不同组合

c++ - 为什么 al_draw_textf() 打印数字而不是存储在字符串变量中的字母?

c++ - 以可变参数函数为参数的函数

将结构体中的字符数组与用户输入的字符数组进行比较

data-structures - Julia:自引用和递归类型

C 返回结构体指针

c - 带有结构体数组的 Malloc