我想在堆上分配一个结构,初始化它并从函数返回一个指向它的指针.我想知道在这种情况下我是否有办法初始化结构的const成员:
#include <stdlib.h>
typedef struct {
const int x;
const int y;
} ImmutablePoint;
ImmutablePoint * make_immutable_point(int x, int y)
{
ImmutablePoint *p = (ImmutablePoint *)malloc(sizeof(ImmutablePoint));
if (p == NULL) abort();
// How to initialize members x and y?
return p;
}
Run Code Online (Sandbox Code Playgroud)
我应该从中得出结论,在包含const成员的堆上分配和初始化结构是不可能的?
caf*_*caf 54
像这样:
ImmutablePoint *make_immutable_point(int x, int y)
{
ImmutablePoint init = { .x = x, .y = y };
ImmutablePoint *p = malloc(sizeof *p);
if (p == NULL) abort();
memcpy(p, &init, sizeof *p);
return p;
}
Run Code Online (Sandbox Code Playgroud)
(注意,与C++不同,不需要malloc
在C中强制转换返回值,并且它通常被认为是错误的形式,因为它可以隐藏其他错误).
Joh*_*ler 11
如果这是C而不是C++,除了颠覆类型系统之外,我没有看到任何解决方案.
ImmutablePoint * make_immutable_point(int x, int y)
{
ImmutablePoint *p = malloc(sizeof(ImmutablePoint));
if (p == NULL) abort();
// this
ImmutablePoint temp = {x, y};
memcpy(p, &temp, sizeof(temp));
// or this
*(int*)&p->x = x;
*(int*)&p->y = y;
return p;
}
Run Code Online (Sandbox Code Playgroud)