Very simple way to understand Structure in C

Structures in C programming language is little bit difficult to get for beginners.

A structure is a user defined data type. There are different data types like integers, float, character etc. A structure allows you to create your own data type.

For example,

A structure called student is as follows.

struc student{

char name[20];

int age;

float marks;

};

Here the name of the structure is called student. As you can see we have used different data types- int, float, marks etc in the structure student. The name, age and marks are called elements of the structure. These elements are of all different data types.

Why to use structure?

Structure is useful to group and use different kinds of variables like students. It is useful to hold information in a variable that has different data types. For example, an array cannot hold different data types. An array can hold only one kind of data types such as integers, floats or chars.

int arr[4] = {1,2,3,4};

The question of why structures in C are called user defined data type is explained now. Consider how you would use integer data type int in usual main program.

void main(void){

int x;

..}

In the above code we have declared variable x as integer data type.

Now we can utilize the same concept while using student structure data type:

void main(void){

struc student y;

..}

Now y in this case is variable of the structure student just like in case of integer data type in first example. Note that the two words struc student together makes a data type.

Once the structure variable y is declared, memory is allocated to it. The memory allocation starts with some base address and adds up the memory taken by the elements of the structure. The structure variable y holds the base address and using the accessor(.) the different element of the structure is accessed. That is why the structure variable y is also called internal pointer variable.

After the structure is created and variable such as y is created, we need to access the value stored in the variable elements or store some value into the variable elements. For example, one might store the age, name and marks of a student and later retrieve them. In C programming language using structure this is done using the accessor. An accessor is a dot operator.

Thus for example you want to give age then you can do this in the following manner.

y.age = 19;

Or you might want to give name,

y.name = John;

 

 

 

 

 

 

 

 

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Leave a Reply

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

Robot Motor control using Arduino

Robot Motor control using Arduino

Easy to understand Pointer in C