Skip to content
Home » All Posts » Create Custom Data Types With the C Struct

Create Custom Data Types With the C Struct

c struct your way

Introduction

A struct is a user-defined data type that represents multiple variables of multiple data types. It is a convenient data type to work with if you require to logically group multiple variables together and represent them in one name (or variable). This is one of the most commonly used data type in small to large C applications. Knowing the principles of struct is absolutely a must.

Define a C Struct

Defining a struct refers to the action of grouping multiple data types into one single name. This can be achieved using the struct keyword enclosed within curly brackets {}. For example:

struct user
{
	int userid;
	char username[64];
	unsigned int age;
	char occupation[64];
};

In the above example, we created a new data type called struct user that contains 4 other variables called, userid, username, age and occupation. A struct can also contain another struct, but you have to ensure that it has already been defined. For example:

struct address
{
	unsigned int house_number;
	char street[128];
	char city[128];
	char state[128];
	char country[128];
};
struct user
{
	int userid;
	char username[64];
	unsigned int age;
	char occupation[64];
	struct address myaddress;
};

In the above example, we added another variable called myaddress inside struct user. myaddress has a custom data type of struct address defined to contain a house_number, street, city, state and country.

Declare a C Struct

What we have done so far above is to define a custom data type using the struct keyword. The next thing to do is to declare a variable using this new custom data type. It can be declared just like a regular variable except that we will use struct user as the data type.

#include <stdio.h>
#include <string.h>

struct address
{
    unsigned int house_number;
    char street[128];
    char city[128];
    char state[128];
    char country[128];
};
struct user
{
    int userid;
    char username[64];
    unsigned int age;
    char occupation[64];
    struct address myaddress;
};

int main()
{
    /* declare variable of type struct user */
    struct user myuser;

    return 0;
}

In the main() function of the above example, a variable myuser is declared as data type struct user without any initial values, also known as “uninitialized”. The next thing we need to do is give it some useful values, and there is a couple ways to do it (also known as “to initialize”).

Initialize a C Struct

There is a couple ways to initialize a struct:

Initialize a struct to all ZERO:

int main()
{
    struct user myuser = {0};
    return 0;
}

Initialize a struct to some initial values for all members – Here we have to use a curly bracket {} and put an initial value one by one in the order they are defined. If another struct is encountered, we need to put another curly brackets with values.

You must specify the initial values in the order as they are defined and use double quote for strings (or char array), single quote for a single character (char), and no quote for integer types.

If you misplace an initialization, or miss one value in between, you initial struct will contain incorrect values. So be careful here.

int main()
{
    struct user myuser = {1, "caryhuang", 30, "techbuddies", {3000, "mystreet", "vancouver", "bc", "ca"}};
    return 0;
}

Initialize a struct to some initial values for partial members – You do not have to put a value for all members in a struct, you can initialize only some of them. But you still have to initialize them in order, and stop where you would like. In other words, you cannot skip the first few values and initialize only the last few members. You have an option to initialize the first few members. The uninitialized members will have random values. For example:

int main()
{
    struct user myuser = {1, "caryhuang", 30, "techbuddies"};
    return 0;
}

Use a C Struct

A C struct can be used in similar way as a regular variable except that:

  • you will need to use the dot operator to access a particular member inside a C struct.
  • you will use the arrow -> operator to access each member if this struct is declared as a pointer.

Otherwise, it behaves just like a regular variable. For example, to assign values for each member in a struct:

#include <stdio.h>
#include <string.h>

struct address
{
	unsigned int house_number;
	char street[128];
	char city[128];
	char state[128];
	char country[128];
};
struct user
{
	int userid;
	char username[64];
	unsigned int age;
	char occupation[64];
	struct address myaddress;
};

int main()
{
    /* declare struct user with all zero */
    struct user myuser = {0};

    /* assign values for each member */
    myuser.userid = 1;
    myuser.age = 30;
    strcpy(myuser.username, "caryhuang");
    strcpy(myuser.occupation, "techbuddies");
    myuser.myaddress.house_number = 3000;
    strcpy(myuser.myaddress.street, "mystreet");
    strcpy(myuser.myaddress.city, "vancouver");
    strcpy(myuser.myaddress.state,"bc");
    strcpy(myuser.myaddress.country,"ca");
    
   /* print values for each member */
    printf("user id %d\nusername %s\nage %u\noccupation %s\nhouse number %u\nstreet %s\ncity %s\nstate %s\ncountry %s\n",
        myuser.userid, 
        myuser.username,
        myuser.age,
        myuser.occupation,
        myuser.myaddress.house_number,
        myuser.myaddress.street,
        myuser.myaddress.city,
        myuser.myaddress.state,
        myuser.myaddress.country);
    return 0;
}

A struct can also be assigned a value based on another struct using the = operator. This means that all members within the struct will be copied.

#include <stdio.h>
#include <string.h>

struct address
{
	unsigned int house_number;
	char street[128];
	char city[128];
	char state[128];
	char country[128];
};
struct user
{
	int userid;
	char username[64];
	unsigned int age;
	char occupation[64];
	struct address myaddress;
};

int main()
{
    /* declare struct user with all zero */
    struct user myuser = {0};
    struct user myuser2 = {0};

    /* assign values for each member */
    myuser.userid = 1;
    myuser.age = 30;
    strcpy(myuser.username, "caryhuang");
    strcpy(myuser.occupation, "techbuddies");
    myuser.myaddress.house_number = 3000;
    strcpy(myuser.myaddress.street, "mystreet");
    strcpy(myuser.myaddress.city, "vancouver");
    strcpy(myuser.myaddress.state,"bc");
    strcpy(myuser.myaddress.country,"ca");
    
    myuser2 = myuser;
   /* print values for each member */
    printf("user id %d\nusername %s\nage %u\noccupation %s\nhouse number %u\nstreet %s\ncity %s\nstate %s\ncountry %s\n",
        myuser2.userid, 
        myuser2.username,
        myuser2.age,
        myuser2.occupation,
        myuser2.myaddress.house_number,
        myuser2.myaddress.street,
        myuser2.myaddress.city,
        myuser2.myaddress.state,
        myuser2.myaddress.country);
    return 0;
}

The above example populates values for myuser, copy its member values to myuser2 and then print the members of myuser2. It should print the same values as myuser.

This direct assignment is true ONLY when both myuser and mysuer2 are declared as a regular variable (not a pointer) and the struct itself does NOT contain any pointer declarations. In the case with pointers, it is more complicated and it is covered in the pointer section.

Recommended Reads

Join the conversation

Your email address will not be published. Required fields are marked *