C Language

What are Structures?

In C Language by Baqir AliLeave a Comment

A structure is a collection of related elements, possibly of different types, having a single name. The elements in a structure can be of the same or different types. But all elements in a structure must be related

A structure type can be defined using the keyword struct. For example,

struct student 
{
	char id[9];
	char name[26];
	float gpa;
};

This defines a new data type called struct student, which consists of three members. However, no variable storage has yet been allocated

Structure Type

Structure variables can be defined just like variables of simple data types. For example,

struct student ali;
structure in c

Global Structure Type

Usually, a struct type is defined globally. For example,

#include <stdio.h>
struct student
{
	char id[9];
	char name[26];
	float gpa;
};
	
int main(void)
{
	struct student ali;
	...
}

More Examples

#include <stdio.h>
struct date 
{
		int day;
		int month;
		int year;
};
int main(void)
{
	struct date today;
	today.day = 1;
	today.month = 1;
	today.year = 2003;
	if (today.day==1 &amp;&amp; today.month==1)
		printf(“Happy New year");
	return 0;
}

Structure The Membership Operator

Members of a struct variable can be accessed using the membership operator (.),  Also called dot operator.

struct var.member

where var is a struct variable and the member is a defined component of the struct.

#include <stdio.h>
struct date 
{
	int day;
	int month;
	int year;
};
int main(void)
{
	struct date today, dob;
	int age;
	printf(“Enter your Date of birth (dd mm yy)? ");
	scanf("%d %d %d", &amp;dob.day, &amp;dob.month, &amp;dob.year);
	printf(“Enter Today (dd mm yy)? ");
	scanf("%d %d %d", &amp;today.day, &amp;today.month, &amp;today.year);
	if (today.month > dob.month 
	    || (today.month == dob.month &amp;&amp; today.day >= dob.day))
			age = today.year - dob.year;
	else
		age = today.year - dob.year - 1;

	printf("Age = %d\n", age);
	return 0;
}

Initializing Structures

struct variables can be initialized as follows:

struct date 
{
	int day;
	int month;
	int year;
};
struct date birthday ={5, 12, 91};

The initial values should be constant values or constant expressions. That is, no variables should be involved in the initializer expressions.  For automatic struct variables, if fewer initializers are listed than the number of members in the struct, the values of the remaining members are undefined.

struct employee 
{
	char name[50];	
	char position;
	float salary;
};
struct employee emp1={“Ali ", ‘M', 8900.5};

Alternative struct Declarations

typedef struct 
{
	char id[9];
	char name[26];
	float gpa;
} STUDENT;
STUDENT ali;

This defines the data type of STUDENT, which is a struct. Note that

STUDENT ali; 

is sufficient; rather than

struct STUDENT ali; 

Leave a Comment