Suhail Gupta
Suhail Gupta

Reputation: 23226

errors while trying to pass a structure to a function

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++

Upvotes: 1

Views: 1386

Answers (3)

Muku
Muku

Reputation: 562

The thing is you're trying to compile with gcc, which is a "c language" compiler and you're following C++ style of code.
It is possible to create a struct variable by just structname variablename;
but in c++, you explicitly have to tell the compiler it is a struct like
struct structname variablename; Just do that and you'll be fine, otherwise you can use a typedef which is basically you tell the compiler form now on you are going to call struct tester to only tester, which will suit you more since you only have to only a minor change.

Upvotes: 0

Florin Stingaciu
Florin Stingaciu

Reputation: 8285

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.

Upvotes: 5

Minion91
Minion91

Reputation: 1929

your struct isn't named. either use struct tester t; or usa a typedef

Upvotes: 1

Related Questions