【问题标题】:C struct-to-struct assignment - incorrect values in target structureC struct-to-struct assignment - 目标结构中的值不正确
【发布时间】:2011-06-14 04:38:32
【问题描述】:

我在头文件中有一个 c 结构:-

typedef struct sample
{
char *member1;
char **member2;
long *member3;
unsigned int member4;
} example;

我已经在同一个头文件中声明了一个默认的 typedef 变量:-

const example defaultValue;

defaultValue的定义在c文件中:-

const example defaultValue = 
{
NULL,
NULL,
NULL,
99
};

如果我这样做,现在在不同的 c 文件中,

example example1 = defaultValue;

所有成员都按预期分配为 NULL - 但是“unsigned int member4”被分配的值为 0 而不是 99。这很奇怪,因为 defaultValue.member4 是 99。有人可以解释一下这种不寻常的行为吗?有没有更好的方法来进行默认结构初始化?

【问题讨论】:

  • 您发布的代码甚至无法编译。你可能还错过了其他东西。
  • 确保在您的其他文件中正确引用了第二个 const。如果不是,您最终会得到(很可能)example1 被零填充。
  • 请编辑您的帖子以从您的实际源文件中复制代码。正如一些人所观察到的,您发布的代码不可能编译 - 更不用说给出您报告的行为了。所以帮助你是不可能的,因为我们不得不猜测你的代码可能是什么样子。
  • @martin..抱歉帖子不正确 - 快速示例。已编辑。

标签: c structure variable-assignment


【解决方案1】:

你会希望你的头文件像这样声明defaultValue

extern const example defaultValue;

这样您就不会遇到多个对象定义的问题。如果没有extern 说明符,您将让每个翻译单元(包括标题)定义defaultValue 的实例,这会导致未定义的行为。

您希望它们都引用您在问题中描述的 .c 文件文件中的那个,这就是 extern 说明符将为您做的事情。

【讨论】:

  • @Michael..非常感谢您的快速回答。是的,我错过了外部。它现在工作正常。再次感谢。
【解决方案2】:

您的示例似乎包含几个错误(struct 缺少其r,并且结构的字段定义应以分号而不是逗号结尾)。

此外,如果您的 defaultValue 在另一个源文件中,您应该在标题中将其声明为 extern

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多