C – Structures – POFTUT

C – Structures

[rps-include post=6557]

C provides primitive data types like int , char , float etc. But in order to solve real world problems we need more than these types. Newer object oriented languages have a lot of features to implement real world situations. For example C++ provides Object Oriented features where we can implement real world objects. C lacks of these features but provides struct type. Struct is used to provide composite data type which can provides multiple primitive types.

Defining Structure

Defining a struct is similar to union. We will provide the elements we want to store in a struct and the name of the struct like following syntax.

Syntax can provide some hint about struct but the best way to understand and learn is defining struct as a real world example. In this example we will create a struct named Student which have following members.

  • name holds student name as char variables
  • id holds student id as int

We have used only two member to make things simple but there is not limit about the members other than memory.


We can initialize new structs variables like below just providing the struct keyword with the struct name and the variable name we want to use. Here we create a struct named s1 with Student struct type.

Accessing Structure Members

We have defined struct members id and name . We need to set and get these members values.We can simply access them with the struct variables name and the member name.

LEARN MORE  Memcached Get Operation with Python Example

We have set the id with the following line

We can also access same syntax to the id variable like below.

Structure As Function Arguments

We have seen that structures provide good flexibility. We generally use structures to pass values to the functions. In this part we will look how can we pass structure variable to the function. We need to define struct parameter as function argument like defining normal struct.

[rps-include post=6557]

Leave a Reply

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

Enjoy this blog? Please spread the word :)