【发布时间】:2021-09-29 02:40:05
【问题描述】:
此代码是否有未定义的行为,这意味着对于 s 是强制分配内存还是可以这样? PS:两者有什么区别
struct X* x = (struct X*)malloc(sizeof(struct X));
and
struct X* x = (struct X*)malloc(sizeof(x));
and
struct X* x = (struct X*)malloc(sizeof *x);
谢谢。
#include <stdio.h>
#include <stdlib.h>
struct X
{
int x;
char* s;
};
int main()
{
struct X* x = (struct X*)malloc(sizeof(struct X));
x->x = 10;
// x->s = (char*)malloc(10);
// memcpy...
x->s = "something";
printf("is ok?");
return 0;
}
【问题讨论】:
-
第一个是正确的,因为它分配了正确的字节数来保存结构。另外两个只分配指针大小的内存:4 或 8 字节。你真的不需要 malloc 上的
(struct X*),因为结果与所有指针类型兼容。虽然它会起作用(并且是样式问题),但声明指向结构的指针的常规方法是struct X x*。