Reputation: 163
I am trying to understand the concept of struct and typedef in C. SO i created this simple program, but for some reason it is not working.
#include <stdio.h>
#include <stdlib.h>
typedef struct testT{
int number;
} testT;
int main()
{
testT.number=10;
printf("%d", testT->number);
}
However, it is giving me error: expected identifier or '(' before '.' token Why is this showing up?
Thanks
Upvotes: 0
Views: 129
Reputation: 7944
typedef struct testT {
int number;
} testT;
Defines a type called testT
, which when used like so:
testT aTestStruct;
Is functionally equivalent to (an anonymous struct type):
struct { int number } aTestStruct;
The typdef just allows us to save ourselfs from having to repeat the anonymous struct declaration syntax of struct { ... }
each time.
Upvotes: 0
Reputation: 4366
No, typedef struct xxx { ... } yyy;
is not 'a C++ syntax', it is a correct C syntax.
What you are doing here is defining a type called testT
which represents a struct testT
being a struct containing a field of type int
called number
.
What you need to do to use this type is declare a variable of that type:
int main(void)
{
testT variable;
variable.number = 10;
printf("%d\n", variable.number);
}
->
notation is used to replace (*).
. For example :
//With variable declared like this :
testT *variable;
//You can write:
variable->number
//Or:
(*variable).number
Upvotes: 1
Reputation: 106012
testT
is a type. First declare a variable of type testT
testT t;
And do not forget to change
printf("%d", testT->number);
to
printf("%d", t.number);
Upvotes: 0
Reputation: 22542
Both struct <name>
and typedef <type> <name>
only define types. You have to actually allocate memory to hold an instance of that type:
int main()
{
struct testT a;
a.number=10;
printf("%d", a.number);
}
Also you are misusing the ->
operator. This is only useful with pointers to structs.
int main()
{
struct testT a;
struct testT *b = &a;
a.number=10;
printf("%d", b->number);
}
b->number
is equivalent to (*b).number
;
Upvotes: 1
Reputation: 8022
You need to create an instance of your struct. You've defined it, but you need to instantiate it.
testT mytestT;
mytestT.number=10;
...
Upvotes: 1
Reputation: 122383
testT
is a type, just like int
, you need to use a variable:
testT t;
t.number=10;
printf("%d", t.number);
Also note that you should use dot operator .
because the arrow operator ->
is used on a pointer to struct
.
Upvotes: 5