尝试将结构传递给函数时出错

Suh*_*pta 1 c linux gcc compiler-errors structure

在下面的程序中,我尝试将结构传递给函数.但我得到错误,我不明白为什么.我在这个程序中犯了什么错误?

gcc用来编译这个c程序.

#include <stdio.h>

struct tester {
  int x;
  int *ptr;
};

void function(tester t);

int main() {
 tester t;
 t.x = 10;
 t.ptr = & t.x;
 function(t);
}

void function(tester t) {
   printf("%d\n%p\n",t.x,t.ptr);
}
Run Code Online (Sandbox Code Playgroud)

错误:

gcc tester.c -o tester

tester.c:8:15: error: unknown type name ‘tester’
tester.c: In function ‘main’:
tester.c:12:2: error: unknown type name ‘tester’
tester.c:13:3: error: request for member ‘x’ in something not a structure or union
tester.c:14:3: error: request for member ‘ptr’ in something not a structure or union
tester.c:14:13: error: request for member ‘x’ in something not a structure or union
tester.c: At top level:
tester.c:18:15: error: unknown type name ‘tester’
Run Code Online (Sandbox Code Playgroud)

: 如果我更换printfcoutstdioiostream和命名扩展.cpp(!),我没有得到任何错误.这是为什么 ?难怪我用它编译它g++

Flo*_*ciu 5

如果你不键入结构,你必须在结构名称前面指定struct,同时声明它:

struct tester t;
Run Code Online (Sandbox Code Playgroud)

您可以这样做,也可以执行以下操作:

typedef struct {
  int x;
  int *ptr;
}tester;
Run Code Online (Sandbox Code Playgroud)

更新

以下是来自以下帖子的Adam Rosenfield的引用:C++中'struct'和'typedef struct'之间的区别?:

在C++中,所有struct/union/enum/class声明都像隐式typedef一样,只要该名称不被另一个具有相同名称的声明隐藏.