C Structure | Difference Between Array and Structure | Learn C

C Structure

When we write a program, it is important to choose an optimal and best way to represent the data that further use in program. In general, scalar variables and arrays are sufficient. For example, in your program, you may want to refer to a student that holds multiple fields including Roll number, name, age, city, state and country. That’s why c structure is important.

In C there is a special kind of variable called structure. C structure allows you to wrap related variables that has different data types (User Defined Datatype) into a single variable. A structure can contain any valid data types such as  int, char, float, array or even other structures. Each variable in the structure is called structure member.


Defining a Structure

To define a structure, you use the struct keyword. The following illustrates the syntax of the structure:

The name of structure must follow the rules of variable name. The following example defines the Student structure:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variables:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure

1st Method

2nd Method


Difference Between Array and Structure

Array Structure
1 Array is collection of homogeneous data like int a[10] or char[50] etc. Structure is the collection of heterogeneous data.

struct Student

{

 int Roll_no;

char Name[50];

};

2 Array data are access using index.

Example:

int a[0];

int a[1];

……

Structure elements are access using . operator.

Example:

Student s1;

s1.Roll_No;

s1.Name;

3 Array allocates static memory. Structures allocate dynamic memory.
4 Array element access takes less time than structures. Structure elements takes more time than Array.

Leave a Reply

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