How to create a struct and its object in C

About C Struct (Structure)

In C programming, a struct is a user-defined data type that is used to group variables of different types under a single name.

It is useful for organizing related data items into a single entity.

It makes code more readable and manageable when dealing with complex data types.

The 'struct' is the short for 'structure'.

Syntax of 'struct'

  • struct StructName: The 'struct' keyword defines the 'struct'. The 'StructName' is the name of the structure and it will be replaced by the user defined name.
  • dataType member1;: The 'dataType' is the data type of the member (variable) of structure and the 'member1' is name of the member (variable) of the structure. The 'member1' will be replaced by the user defined name.
  • struct StructName variableName;: The 'struct' is the keyword and 'StructName' is the name of the struct. 'StructName' will be followed by the 'variableName' and it will be replaced by the user defined variable name.

Create a 'struct'

A 'struct' and it object have been created in the following example:

Example of Creating a Struct
Output of the above example
John
30

Explanation of code:

  • struct Person { char name[50]; int age;};: This defines a struct name 'Person'. The 'Person' struct has two members: 'name' and 'age'.
  • struct Person personObj;: This declares a variable of Person Struct named 'personObj'.
  • strcpy(personObj.name, "John");: This initializes the 'personObj' member 'name' with value "John". The 'strcpy' function is used to assign the value "John" to 'personObj.name' member by copying.
  • personObj.age = 30;: This initializes the 'personObj' member 'age' with value 30.
  • printf("%s\n", personObj.name); and printf("%d\n", personObj.age);: These are used to access members of 'personObj' and print their vaules.
  • Please note that to access a member of struct a period (.) is used between variable (object) of struct and its member.

Live Code Playground

In the following C code editor, you can practice by creating more struct or updating the struct with more members. Click the 'Execute Code' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output