2012-08-06 49 views
3

这是我的代码:问题初始化一个struct

typedef struct{ 
    char name[64]; 
} Cat; 

Cat createCat(char name[64]) { 
    Cat newCat; 

    int i; 

    for(i = 0; i < 64; i += 1) { 
    newCat.name[i] = name[i]; 
    } 

    return newCat; 
} 

Cat exampleCat = createCat("Bob"); 

它编译并出现以下错误:

initializer element is not constant

我在做什么错?

回答

6
Cat exampleCat = createCat("Bob"); 

你不能在这里做一个方法调用。在其他地方初始化exampleCat

这在规范中进行了说明,部分6.7.8/4:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

+3

+1,“别的地方” - 里面的方法 – Mysticial 2012-08-06 15:42:48

+0

这仍然只有一半的答案,连同博的它将使一个完美的:) – 2012-08-06 18:25:35

+0

@JensGustedt:但他们没有相同的功能。 – Ryan 2012-08-06 21:59:53

0

尝试,而不是:

void createCat(Cat * kitty, char name[64]) { 
    int i; 

    for(i = 0; i < 64; i += 1) { 
    kitty->name[i] = name[i]; 
    } 
} 

Cat exampleCat; 
createCat(&exampleCat, "Bob"); 
+0

尝试在全局作用域调用函数的问题仍然存在 – 2012-08-07 20:41:49

+0

您不能通过添加空行来分隔代码块。所以我不会添加无意义的填充符,而只是让提问者使用他的大脑。 – Wug 2012-08-07 20:43:23

2

你真的不需要写一个函数来初始化一个结构。你可以使用一个初始值设定项,给每个成员赋值(这里只有一个)。

Cat exampleCat = {"Bob"}; 

还要注意的是,如果你不是曾使用C++,你就必须使用动态初始化的选项,并且代码将是确定的。