【问题标题】:How to declare a struct in c?如何在c中声明一个结构?
【发布时间】:2014-09-12 13:56:05
【问题描述】:

我正在关注这个example,我的程序如下所示:

#include <string.h>
#include <stdio.h>
#include <stdlib.h> 

struct Foo
{
    int x;
    int array[100];
}; 


struct Foo f;
f.x = 54;
f.array[3]=9;

void print(void){

    printf("%u", f.x);
}

int main(){
    print();
}

但是,我在使用 make example_1 编译时遇到错误:

example_1.c:13:1: error: unknown type name 'f'
f.x = 54;
^
example_1.c:13:2: error: expected identifier or '('
f.x = 54;
 ^
example_1.c:14:1: error: unknown type name 'f'
f.array[3]=9;
^
example_1.c:14:2: error: expected identifier or '('
f.array[3]=9;
 ^
4 errors generated.
make: *** [example_1] Error 1 

这个结构声明有什么问题?

【问题讨论】:

  • 您不能在函数之外编写可执行代码。将 3 行 struct Foo f; ... f.array[3]=9 放入 main()

标签: c arrays struct initialization


【解决方案1】:
f.x = 54;
f.array[3]=9;

应该在某个函数内部。除了初始化之外,您不能在全局范围内编写函数外的程序流。

要全局初始化它,请使用

struct Foo f = {54, {0, 0, 0, 9}};

live code here

在C99中,你也可以写

struct Foo f = {.x=54, .array[3] = 9 };

live code here


你提到的示例链接说:

结构 Foo f; // 自动分配,所有字段都放在stack
f.x = 54;
f.array[3]=9;

字堆栈的使用表明它开始在本地函数中使用,如下所示:

void bar()
{
  struct Foo f;
  f.x = 54;
  f.array[3]=9;
  do_something_with(f);
}

live example here

【讨论】:

    【解决方案2】:

    您只能在结构变量的声明点初始化它。

    你可以这样初始化它:

    struct Foo f = {54, {0, 0, 0 9}};
    

    或使用 C99 功能designated initializers

    struct Foo f = {.x = 54, .array[3] = 9};
    

    第二种方法更清晰,但不幸的是,C99 不如 C89 广泛可用。 GNU 编译器完全支持 C99。 Microsoft 的编译器不支持 C89 以上的任何 C 标准。 C++ 也没有这个特性。

    因此,如果您希望代码使用 C++ 编译器或 Microsoft 的 C 编译器进行编译,您应该使用第一个版本。如果您纯粹为 gcc 编写代码并且不太了解 Microsoft 的开发工具,您可以使用第二个版本。

    您还可以在函数中单独分配每个成员:

    void function(void)
    {
        f.x = 54;
        f.array[3] = 9;
    }
    

    但你不能在全球范围内做到这一点。

    【讨论】:

    • 在我开始写这篇文章的时候,另一个答案并没有建议designated initializers。在我发布此内容后,我注意到另一个答案已被编辑以包含该内容。这个答案现在似乎是多余的。我不知道该怎么办。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2013-06-23
    • 2021-12-13
    • 2021-03-10
    • 1970-01-01
    • 2023-02-25
    相关资源
    最近更新 更多