我不知道下一个任务意味着什么:
struct reportItem * itemCopy = (struct reportItem *) malloc(sizeof(struct reportItem))
有人可以一步一步向我解释这个作业吗?实在不知道什么意思。
谢谢
最佳答案
struct reportItem *itemCopy = (struct reportItem *) malloc(sizeof(struct reportItem));
// ^^^^^^^^^^^^^^^^^^^^^
强制转换是不必要的,并且可能会隐藏编译器在没有强制转换时会捕获的错误 (1)
struct reportItem *itemCopy = malloc(sizeof(struct reportItem));
// ^^^^^^^^^^^^^^^^^^^
在这里使用类型本身可能会被视为“等待发生的事故”(2)。使用对象本身更安全
struct reportItem *itemCopy = malloc(sizeof *itemCopy);
所以现在这是一个很好看的声明:)
这会调用库函数malloc()
(它尝试保留一个内存区域供程序使用)并将结果值分配给 itemCopy
.
程序员有责任检查malloc()
是否有效。设法在使用该内存之前保留该内存。
if (itemCopy == NULL) {
//malloc failed to reserve memory
fprintf(stderr, "no memory.\n");
exit(EXIT_FAILURE);
}
此外,一旦不再需要内存,程序员就有责任释放内存(返回到操作系统)。
//use itemCopy
free(itemCopy);
<小时/>
(1) 强制转换隐藏错误
如果malloc()
范围内没有原型(prototype)编译器假设它返回 int
。然后,用强制转换默默地转换非法int
(非法,因为它实际上是一个 void*
值)到指针。 错误是缺少 #include <stdio.h>
和 Actor 阵容。如果您只是删除强制转换,编译器会提示 int
的转换。到指针。如果您#include <stdio.h>
并保留类型转换,它是多余的(冗余是不好的)。
(2) 使用类型来确定要分配的内存量是“等待发生的事故”
调用malloc(sizeof(struct whatever))
是一种“等待发生的事故”,因为它迫使程序员通过单个结构更改在多个地方更改代码。
让我们想象有一个 struct Car
具有一些属性...后来决定将部分代码更改为新修改的 struct Vehicle
(同时保持 struct Car
处于事件状态)。使用 malloc()
中的类型名称调用强制 2 项更改
struct Vehicle *x = malloc(sizeof (struct Vehicle));
// ^^^^^^^^^^^^^^^^ prevented accident
使用对象时只需要进行一次更改
struct Vehicle *x = malloc(sizeof *x);
// ^^ *x is of the correct type
关于c - 理解 C 中的结构体和指针变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52794280/