尝试将结构传递给函数时发生错误 [英] errors while trying to pass a structure to a function

查看:161
本文介绍了尝试将结构传递给函数时发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我使用 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;
函数(t);


void function(tester t){
printf(%d\\\
%p\\\
,t.x,t.ptr);






错误:

  gcc tester.c -o tester 

tester.c:8:15:error:unknown type name'测试仪'
tester.c:在函数'main'中:
tester.c:12:2:错误:未知类型名称'tester'
tester.c:13:3:error:请求成员'x'的东西不是结构或联合
tester.c:14:3:错误:成员'ptr'的请求不是结构或联合
tester.c:14: 13:错误:请求成员'x'的东西不是结构或联合
tester.c:顶层:
tester.c:18:15:错误:未知类型名称'tester'

注意使用 cout stdio iostream printf / code>并将扩展名命名为 .cpp (!),我没有遇到任何错误。这是为什么 ?难怪我用 g ++

来编译它

解决方案

typedef结构体,你必须在结构体名前面指定结构体,同时声明它:

  struct tester t; 

要么你这样做,要么做以下操作:

  typedef struct {
int x;
int * ptr;
}测试人员;

更新

<下面是Adam Rosenfield从以下文章中引用的一段引文 struct'和'typedef struct'in C ++?
$ b


在C ++中,所有struct / union / enum / class声明就像它们是隐式的typedef,只要这个名字不被具有相同名字的另一个声明隐藏。



In the following program I try to pass a structure to a function. But I get errors,and I do not understand why. What mistake have I made in this program ?

I am using gcc for compiling this c program.

#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);
}


Errors :

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’

NOTE : If I replace printf with cout and stdio with iostream and name the extension to .cpp (!), I get no errors. Why is that ? No wonder I compile it using g++

解决方案

If you don't typedef the struct you must specify struct in front of the struct name while declaring it like so:

struct tester t;

Either you do that or you do the following:

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

Update

Below is a quote from Adam Rosenfield from the following post Difference between 'struct' and 'typedef struct' in C++?:

In C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.

这篇关于尝试将结构传递给函数时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆