如何在c中声明一个结构?

Pip*_*ppi 0 c arrays struct initialization

我正在关注这个例子,我的程序看起来像这样:

#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();
}
Run Code Online (Sandbox Code Playgroud)

但是,编译时我遇到错误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 
Run Code Online (Sandbox Code Playgroud)

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

Moh*_*ain 6

f.x = 54;
f.array[3]=9;
Run Code Online (Sandbox Code Playgroud)

应该在里面一些功能.除初始化外,您不能在全局范围内编写函数外的程序流.

要全局初始化,请使用

struct Foo f = {54, {0, 0, 0, 9}};
Run Code Online (Sandbox Code Playgroud)

现场代码

在C99中,您也可以写作

struct Foo f = {.x=54, .array[3] = 9 };
Run Code Online (Sandbox Code Playgroud)

现场代码


您提到的示例链接说:

struct Foo f; //自动分配,所有字段都放在堆栈上
f.x = 54;
f.array[3]=9;

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

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

这里的实例