[C] Struct Types

In C, related data can be grouped as a single type using the “struct” keyword. It is short for “structured data type“.

 

1. Declaring and Using Struct

You can  use a struct type in the following 2 steps:

  • Declaring it
  • Creating a variable of it
struct Person
{
  const char *Name;
  int Age;
};

void TypeTest1()
{
  struct Person homer = { "Homer Simpson", 0 };
  homer.Age = 36;

  printf("Name = %s, Age = %i n", homer.Name, homer.Age);
}

Note that you can use the “.” notation to access a member of a struct type.

 

2. Giving a Type Name to Struct

It might be cumbersome to use the “struct” keyword whenever you define or use a struct type. The solution is to create an alias with “typedef“.

typedef struct
{
  const char *Name;
  int Age;
} Person;

void TypeTest1()
{
  Person homer = { "Homer Simpson", 0 };
  homer.Age = 36;

  printf("Name = %s, Age = %i n", homer.Name, homer.Age);
}

Now you do not need to specify “struct” when you create variables.

 

3. Using Pointers to Struct Types

What if you want to pass a struct variable to function for updating the values? By default, a struct is copied and passed by value. So if you want to update the value, you need to pass a pointer to a struct value.

You can access a member through a pointer using the “->” operator.

void MakeOneYearOlder(Person *p)
{
  p->Age += 1;
}

void TypeTest2()
{
  Person homer = { "Homer Simpson", 36 };
  MakeOneYearOlder(&homer);

  printf("Name = %s, Age = %i n", homer.Name, homer.Age);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s