在 C 中创建和打印基于指针的结构

标签 c pointers

我刚刚开始学习结构,我已经能够让它们在使用常规变量时正常工作。但是,当我尝试使用指针执行此操作时,我的程序将运行但会崩溃。我确定我只是出了点小问题......

struct Student{
char firstName[30];
char lastName[30];
float gpa;
int id;
};


int main()
{
struct Student *student;
student = (struct Student*)sizeof(struct Student);
strcpy(student->firstName,"Marlop");
strcpy(student->lastName,"smiitlh");
student->gpa = 4.54;
student->id = 45893;

printf("%s",student->firstName);

return 0;
}

最佳答案

这段代码

student = (struct Student*)sizeof(struct Student );

没有意义。这是为 student 分配一些(无效的很可能)无意义的地址。

您应该使用malloc() 来分配一些内存。试试这个:

#include <stdio.h>
#include <stdlib.h>

struct Student{
    char firstName[30];
    char lastName[30];
    float gpa;
    int id;
};


int main(void)
{
    struct Student *student;
    student = malloc(sizeof(struct Student));
    strcpy(student->firstName,"Marlop");
    strcpy(student->lastName,"smiitlh");
    student->gpa = 4.54;
    student->id = 45893;

    printf("%s",student->firstName);

    free(student);
    return 0;
}

关于在 C 中创建和打印基于指针的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33906632/

相关文章:

c - 如何从实现文件访问头文件中定义的结构?

c++ - USACO 牛栏板 : Dinic's Algorithm/Changes to Pointer Not Registering

python - 模拟 python 类属性的类似指针的行为

c - 如何重现 C99 中的类方法行为?

c - 如何使用 LLIST *mylist[N];

C 指向数组的 union 指针

c - 将 .a 库添加到 cmake 项目

c -\b 和\a 在 xcode 上不起作用,但在终端上可以。为什么会这样呢?

c# - 浮点到 int 而不转换为 int

c - 如何删除m25p40闪存的单个页面而不删除其他页面?