【问题标题】:Initialising C struct expected an expression初始化 C 结构需要一个表达式
【发布时间】:2012-04-04 09:59:47
【问题描述】:

我有一个包含大约 17 个成员 struct settings currentProfile 的 C 结构,并希望将其所有成员初始化为零。 (我已经尝试过使用超级正确的结构语法和 typedef 语法)

要将所有成员设置为零,我使用currentProfile = {0}

在这一行编译器给出错误Expected an expression

我的初始化是否正确? 谢谢

【问题讨论】:

  • 请显示一些显示错误的代码。
  • K n R 书中明确提到了这个概念
  • @MichaelFoukarakis settings currentProfile, newProfile void initProfile (void) { currentProfile = {0}; }
  • @RasmiRanjanNayak 说我没读过 K n R 会很不寻常吗?
  • @Toby:我不是那个意思,你没有读过 K n R。我的意思是,你再读一遍,你就会明白。如果以上陈述伤害了您,我很抱歉。但坦率地说,我不是指你的解释。

标签: c struct initialization


【解决方案1】:

您正在执行(无效)分配而不是初始化。

初始化你的结构对象,所有成员都设置为0

struct settings currentProfile = {0}; 

在声明后将结构对象的所有成员设置为0

memset(&currentProfile, 0, sizeof currentProfile);

【讨论】:

  • 请注意,动态分配的指向成员可能需要在 memset 操作之前为 freed 以避免内存泄漏。
  • @moooeeeeep,初始化不是问题!
  • @Shahbaz 但可能会成为稍后分配的问题。
  • @moooeeeep 或者,如果需要,它们可能会存储在临时指针中,并在 memset 之后重写在 struct 中。
  • @ouah,颂赞这项工作用于声明多个结构,如 settings currentProfile, newProfile = {0}; ?塔
【解决方案2】:

memset(pointer_to_struct, 0, size_of_struct);

#include <string.h>

struct settings currentProfile;
memset(&currentProfile, 0, sizeof(struct settings));

【讨论】:

  • 我也做了同样的事情,但我得到了一个错误,找到下面的代码。 #include #include using namespace std;结构 abc {int x;int y;};结构 abc xyz; int main(){ memset(&xyz, 1, sizeof(struct xyz)); cout
  • 查找 C 代码 #include #include //使用命名空间 std;结构 abc {int x;int y;};结构 abc xyz; int main(){ memset(&xyz, 1, sizeof(struct abc)); //memset(&xyz, 1, sizeof(struct xyz)); // 将 'sizeof' 错误应用到不完整类型 'struct xyz' printf("xyz.x = %d", xyz.x) ; // 给垃圾返回 0;}
  • 它不打印垃圾。 memset 第二个参数是 int 类型,但需要字节(8 位长数字)。你传递 1 所以它的二进制表示是 00000001 => 16843009 等于 00000001000000010000000100000001
猜你喜欢
  • 2014-07-30
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
相关资源
最近更新 更多