C++ 在指向结构的指针中设置数组

标签 c++ arrays struct

我在 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/

相关文章:

javascript - 当第二个数组是第一个数组中的键时,根据另一个数组对一个数组进行排序。

PHP/MYSQL - 将表字段保存为单独的字符串变量

c - 存储到我的文件中的结构没有被覆盖(C)

c# - 你如何在 C# 中直接类型转换一个盒装结构?

c++ - 如何预定义 <atomic> 变量?

c++ - std::map 比较函数和 NULL

c++ - 使用 g++ 构建 64 位可执行文件

C++ mysql setString 不替换准备好的语句中的占位符

c++ - 为什么在将大小为整数变量的数组声明时会出现编译器错误?

C - 如何添加结构成员?