How Do You Print a Struct Data Type?


Heather Bennett

Printing a struct data type in C can be achieved by using the printf() function. A struct is a user-defined composite data type that allows you to group together variables of different types into a single entity. It’s commonly used to represent complex data structures.

In order to print the values stored in a struct, you need to access each member of the struct individually. Let’s consider an example where we have defined a struct called Person with three members: name, age, and city.

Defining the Struct

To define the Person struct, you would use the following code:

struct Person {
    char name[50];
    int age;
    char city[50];

Initializing and Printing Struct Values

To initialize and print the values of a struct, you can follow these steps:

  1. Create an instance of the struct:
    struct Person p;
  3. Assign values to each member of the struct:
    strcpy(, "John Doe");
    p.age = 25;
    strcpy(, "New York");
  5. To print the values, you can use multiple calls to the printf() function:
    printf("Name: %s\n",;
    printf("Age: %d\n", p.age);
    printf("City: %s\n",;

    The output for this code snippet will be:

    • Name: John Doe
    • Age: 25
    • City: New York

    Formatting the Output

    You can format the output by using various formatting options available in the printf() function. For example, to include labels for each value, you can modify the printf() statements as follows:

    printf("Name: %s\n",;
    printf("Age: %d years\n",;

    The modified output will appear as:

    • Name: John Doe
    • Age: 25 years
    • City: New York

    In this way, you can print a struct data type in C using the printf() function. Remember to access each member individually and use proper formatting options to display the output as desired.

    I hope this tutorial has helped you understand how to print a struct data type. Happy coding!

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy