c - 结构指针设置值

标签 c pointers struct

我正在尝试为结构创建一个构造函数,它接受一个指向结构的指针、分配内存并设置字段。但是,当我打印我认为已设置的内容时,我看到这些字段是空的。我也在用C99

void init_student(struct student* student, char* name, int id, float gpa) {
    student = (struct student*) malloc(sizeof(struct student));
    student->name = name;
    student->id = id;
    student->gpa = gpa;
}

最佳答案

您正在将函数参数分配给 student。函数参数按值传递,因此调用者永远看不到您分配的内存。为此,您需要修改调用者的变量,您可以通过将指针传递给来实现:

void init_student(struct student** student, char* name, int id, float gpa) {
    *student = malloc(sizeof(struct student));
    ...
}

并将其命名为

struct student* student;
init_student(&student, ...);

或者,将指针作为返回值:

struct student* new_student(char* name, int id, float gpa) {
  struct student* student = malloc(sizeof(struct student));
  ...
  return student;
}

然后

struct student* student = new_student(...);

顺便说一句,您不需要强制转换malloc 的结果,在C 中通常不鼓励这样做,因为它可能隐藏有关缺少#include 的警告指令。此外,如果内存不足,malloc 可能会失败。在这种情况下,您不应该尝试取消引用返回的空指针。

关于c - 结构指针设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758403/

相关文章:

c - 使用 C 为 atmega328p 微 Controller 设计 react 定时器

c - 警告 LNK4092 : shared writable section contains relocations

c++ - 了解嵌套结构

c - 我在 c 中找到了纯虚函数的代码。谁能解释一下?

c - 数组中的元素数量是否可能超过编译时定义的数组大小?

c - 如何让 Mac OS X CrashReporter 调用调试器?

CSV文件读取问题: with large amont of data

c++ - 如何保持存储在作为参数传递的指针中的地址在所有函数调用中保持一致

objective-c - 指针在 C 和 Objective C 中的使用方式不同吗?

c - 结构指针丢失数据