Learning to Write Structures in C

Here is two ways to write structures in C programming language

Structures are used to group and hold variables, usually of different data types, in a single entity. Doing so we create a new data type. Then defining new structure variable, also called instance of structure, we can use the variables in the structure. There are different ways to write Structures and here we illustrate two common ways.

Consider Engineering College which has records for boys and girls engineers. We can write the structure for boys engineer and girls engineers each of which has elements like name, age, marks. Then in the main program we can instantiate structure variable and access, assign values to the different elements of the structures. See the following code example.

 

In this example we create two structures called boys and girls. In case of boys we wrote the optional boys tag after the keyword struct. In the second example, for girls, we used the keyword typedef and named the structure type girls after the end of the curly braces.

In the main program, we created and instance engg1 of the boy structure using struct boys. Similarly we created an instance engg2 of girls structure using just girls. Then we accessed and assigned the elements of the structures using the dot operator.

Finally we printed out the elements values using printf statements.

The output is shown below.

So in this way you can create structures, create instances of a structure and access/assign values to the elements of a structure.

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 *

How to set compiler for code blocks

How to set compiler for code blocks

Difference between function call by value and call by reference