Structures in C

Previous
Next

Primitive types:

  • Using primitive variables, we can store only 1 value at a time.
  • To store more than one value, number of variables need to be declared.
  • It is complex to work with number of variables in the program.
  • For example,
    • Int A;
    • A=10;
    • A=20;
    • Print(A);

Derived types:

  • Array is a derived data type.
  • We can store more than one element into a single variable.
  • For example,
    • Int arr[5] = {10, 20, 30, 40, 50};
  • Drawback: We can store only homogenous data elements, hence we cannot store records.

User defined types:

  • Structures and Unions are called User defined data types.
  • We can store more than one element of different types.
  • We can store records information
    • Employee details
    • Student details
    • Account details.

Creating the structure: “struct” is a keyword and is used to define Structure or Union.

  • Structure gets memory when we declare variable for that structure.
  • Structure block size is equals to sum of each element size defined in that structure.
  • Just like array, structure variable holds the base address of memory block.
  • We can initialize the structure directly using assignment operator.
  • How we assign values to array, in the same way we can assign values to structure.
  • While assigning, we need to follow the order of structure elements.
#include<stdio.h>
struct Emp
{
	int no;
	char name[20];	
	float salary;
};
int main()
{
	struct Emp x = {101, "amar", 50000};	
	printf("No : %d \n", x.no);
	printf("Name : %s \n", x.name);
	printf("Salary : %f \n", x.salary);
	return 0;	
}
Previous
Next

Add Comment

Courses Enquiry Form