我在 C++ 中有一个结构如下:
typedef struct DIFDict
{
std::string name;
std::string defs[];
struct DIFColor *colors[];
uint8_t defsize;
} DIFDict;
问题在于尝试初始化它。我有一个函数,它返回一个指向所有值都已初始化的结构的指针:
struct DIFDict *CreateDIFDict(std::string n, std::string *d, struct DIFColor **c, uint8_t de)
{
int memsize = sizeof(n) + sizeof(d) + sizeof(c) + sizeof(de);
struct DIFDict *i = static_cast<struct DIFDict*>(malloc(memsize));
if(i != NULL)
{
i->name = n;
i->defs = d;
i->colors = c;
i->defsize = de;
}
return i;
}
但是,编译器会提示类型不匹配:
error: incompatible types in assignment of 'std::string {aka std::basic_string<char>}' to 'std::string [0] {aka std::basic_string<char> [0]}'
error: incompatible types in assignment of 'DIFColor**' to 'DIFColor* [0]'
我是不是误解了指针和数组之间的关系?
最佳答案
typedef struct DIFDict
{
std::string name;
std::string *defs;
struct DIFColor **colors;
uint8_t defsize;
} DIFDict;
struct DIFDict *CreateDIFDict(std::string n, std::string *d, struct DIFColor *c, uint8_t de)
{
DIFDict *i = 0;
i = new DIFDict;
if(i != 0)
{
i->name = n;
i->defs = d;
i->colors = &c;
i->defsize = de;
return i;
}
return 0;
}
编辑:上面答案的问题是DIFColor
参数是一个临时参数,函数退出时指向临时参数的指针将无效。一个更可行的(不是最好的,但至少是可行的)与上述方案非常相似的解决方案如下:
struct DIFDict
{
std::string name;
std::string *defs;
DIFColor **colors;
uint8_t defsize;
};
DIFDict *CreateDIFDict(const std::string& n, std::string *d,
DIFColor **c, uint8_t de)
{
DIFDict *i = new DIFDict;
i->name = n;
i->defs = d;
i->colors = c;
i->defsize = de;
return i;
}
请注意,我们现在不获取临时地址——我们只是直接传递指针值并对其进行分配。另外,请注意 new
不会在失败时返回 0(除非使用 nothrow
选项),因此不需要检查 new
是否为 0 .
但是,这个解决方案仍然是类 C 的并且容易出错,并且有更好的方法,正如其他答案所概述的那样。
关于C++ 在指向结构的指针中设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005949/