Hi,

Please suggest me all possible ways of declaring structures in my C codes. I want to be able to create a structure which I can use in my methods without have to use the keyword "struct" each time to declare it. One way I already know of is :

typedef struct
{
	char firstName[50];
	char lastName[50];
}Person;

Creating it this way, I can use it in other methods like this (which is what I want, without using the struct keyword to declare) :

Person person1;

However, the problem I'm facing with this is that I can't get it to work when I want to create a member variable in the struct which is of it's own struct type. This is what I'm trying :

typedef struct
{
	char firstName[50];
	char lastName[50];
	Person firstPerson;
	Person secondPerson;
}Person;

And, obviously this doesn't compile. Would anybody please have a suggestion on how to accomplish this ?

As my question says, I'm still new to C. Please help !

Recommended Answers

All 4 Replies

predeclare the structure

typedef struct tagPerson Person;
struct tagPerson
{
  // blabla
};

Wow !
This works.
Thanks, Ancient Dragon !

Can somebody please explain me though, what is "tagPerson" and "Person" in this case ? As I understand, "tagPerson" is the structure which we defined with it's member variables. But I'm confused about "Person" in this case. Is this a new "type" that is derived from "tagPerson" ? Or is this a variable of type "tagPerson" ? Someone please clarify!!

Person is the same thing that you originally posted. Its just another name for struct tagPerson Person is not an instance of the structure, but just a typedef for it.

@jay1648

typedef struct tagPerson
{
	char firstName[50];
	char lastName[50];
	Person firstPerson;
	Person secondPerson;
}Person;

won't compile because Person struct cannot have a variable of type Person in it, rather it should be a pointer to Person like:

typedef struct tagPerson
{
	char firstName[50];
	char lastName[50];
	tagPerson* firstPerson;
	tagPerson* secondPerson;
}Person;

This code piece combines snippet suggested by Ancient Dragon in one :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.