Structure In C Programming – POFTUT

Structure In C Programming

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 programming lacks these features but provides type. A struct is used to provide composite data type which can provide multiple primitive types.

Defining Structure

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

The 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 the following members?

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

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

Initialize Struct

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 Append Operation with Python Example

We have set the id with the following line

echo '

We can also access the 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 at how can we pass the structure variable to the function. We need to define a struct parameter as function argument like defining a normal struct.

Leave a Reply

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