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.

struct [STRUCT_NAME] { 
MEMBER
... 
} STRUCT_VARIABLES];

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.

struct Student { 
   int id; 
   char name[20]; 
};

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.

struct Student s1;

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.

#include <stdio.h> 
#include <string.h> 
 
struct Student { 
   int id; 
   char name[20]; 
}; 
 
int main( ) { 
 
   struct Student s1;       
 
   s1.id=123; 
   strcpy( s1.name, "Ahmet Ali"); 
 
   printf( "Studen ID : %i\n", s1.id); 
   printf( "Studen Name : %s\n", s1.name); 
 
   return 0; 
}

We have set the id with the following line

s1.id=123;

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

printf( "Studen ID : %i\n", s1.id);

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.

#include <stdio.h> 
#include <string.h> 
  
struct Student { 
   int id; 
   char name[20]; 
}; 
 
 
void print(struct Student s) 
{ 
   printf( "Studen ID : %i\n", s.id); 
   printf( "Studen Name : %s\n", s.name); 
} 
  
 
int main() { 
 
   struct Student s1;         
 
   s1.id=123; 
   strcpy( s1.name, "Ahmet Ali"); 
 
   print(s1); 
 
   return 0; 
}

LEARN MORE  How To Set, Get and Change Bash Environment Variable?

Leave a Comment