codescracker


c

C Structures



« Previous Tutorial Next Tutorial »


The structure is a user-defined data types, allows to combine data items of different types. In other words, the structure is simply a grouping of variables under one name and is called as aggregate data type.

Define a Structure in C

To define a structure in C, just use the keyword struct. The keyword struct simply tells the compiler that a structure is being declared. Here is the general form to define a structure in C:

struct struct_name
{
	type member_name1;
	type member_name2;
	type member_name3;
	.
	.
	.
	type member_nameN;
}structure_variable_name;

Here struct is a keyword used in declaring a structure in C. Then struct_name is the name of the structure. And then type is any valid data type. And then, member_name1, member_name2, member_name3, and member_nameN is the name of the structure members. And in last structure_variable_name is the name of the structure variable used in accessing the the member of this structure using the dot operator. You can also declare structure_variable_name later. You can also follow this general form

struct [structure tag]
{
   member definition;
   member definition;
   member definition;
   ...
   ...
   member definition;
} [structure variables];

Let's look this declaration to understand how to define a structure in C language:

struct address
{
	char name[20];
	char street[40];
	char city[20];
	char state[20];
	unsigned long int zip;
}addr_var;

Here define a structure type called address and declares variable named addr_var of that type. When a structure variable (addr_var here) is declared, then the compiler automatically allocates sufficient memory to accommodate all of its members.

Access Structure Members in C

To access individual members of a structure in C language, then simply use the dot (.) operator. Here is the general form to access structure members in C:

object_name.member_name;

Let's look at the following code fragment, demonstrating how to access structure members:

addr_var.zip = 221001;

And to print the ZIP code on the screen, follow this statement:

printf("%lu", addr_var.zip);

The above statement prints the zip code contained in the zip member of the structure variable addr_var.

Structure Assignments in C

In C, you can also assign one structure to another of same type. In other words, the information contained in one structure can be assigned to another structure of the same type by using a single assignment statement. Here is the general form to assign one structure to another of same type.

struct struct_name
{
	type member_name1;
	type member_name2;
	type member_name3;
	.
	.
	.
	type member_nameN;
} struct_variable1, struct_variable2;

struct_variable1 = struct_variable2;

Here is an example program, demonstrating structure assignment:

/* C Structures - This program demonstrates the
 * concept of structure assignments in C language.
 */

#include<stdio.h>
#include<conio.h>

struct st
{
	int x;
	int y;
	int z;
	char ch;
	char chs[20];
} st1, st2;

void main()
{
	clrscr();

	printf("Enter your name: ");
	gets(st1.chs);
	printf("Enter any three numbers: ");
	scanf("%d%d%d", &st1.x, &st1.y, &st1.z);
	printf("Press y to see the sum: ");
	fflush(stdin);
	scanf("%c", &st1.ch);

	st2 = st1;      // assign one structure to another

	if(st2.ch == 'y' || st2.ch == 'Y')
	{
		printf("%s, the sum of three numbers is %d", st2.chs, st2.x+st2.y+st2.z);
		printf("\n\nPress any key to exit..\n");
		getch();
		exit(1);
	}

	getch();
}

As you can see, this program gets the value entered by the user and stored in the structure members accessed by first structure (structure variable) and then we assign it to another structure (structure variable). So that, all the member's value of first structure can be access using the second structure (structure variable) also. Here is the sample run of the above C program:

c structures

Arrays of Structures

Structures are often arrayed. To declare an array of structures, you have to first define a structure and then declare an array variable of that type. Here is an example declaring a 10-element array of structure of type st:

struct st st_var[10];

Above statement simply creates 10 sets of variables that are organized as defined in the structure st.

To access a specific structure, simply index the array name. Here is example, accessing the member zip of structure 4:

st_var[3].zip;

Here is an example, assigning the value to the member zip of structure 4:

st_var[3].zip = 221001;

Here is an example, printing the value of member zip of structure 4:

printf("%lu", st_var[3].zip);

Here is an example, assigning 'A' to the first character of name in the fourth structure of st_var:

st_var[3].name[0] = 'A';

Let's look at the following example for the complete understanding on the concept arrays of structures in C language:

/* C Structures - This program demonstrates the 
 * the concept of arrays of structures in C */

#include<stdio.h>
#include<conio.h>

struct st
{
	char name[20];
	char street[40];
	char city[20];
	char state[20];
	unsigned long int zip;
};

void main()
{
	struct st st_var[10];
	clrscr();

	printf("Enter name: ");
	gets(st_var[3].name);
	printf("Enter street: ");
	gets(st_var[3].street);
	printf("Enter city: ");
	gets(st_var[3].city);
	printf("Enter state: ");
	gets(st_var[3].state);
	printf("Enter zip code: ");
	scanf("%lu", &st_var[3].zip);

	printf("\nName\tStreet\t\t\tCity\t\tState\tZip Code\n");
	printf("%s\t%s\t\t%s\t%s\t%lu", st_var[3].name, st_var[3].street, st_var[3].city, st_var[3].state, st_var[3].zip);

	getch();
}

Here is the sample run of the above C program:

c structures example

Pass Structures to Functions in C

In C language, you are free to pass structure members to functions or even the entire structures to functions. Whenever you pass a member of a structure to a function, you are passing the value of that member to the function. Let's look at the following structure declaration:

struct st
{
	int num;
	char ch;
	char str[20];
} st_var;

Here is an example passing the each member to a function:

function(st_var.num);     // passes integer value of num
function(st_var.ch);      // passes character value of ch
function(st_var.str[3]);      // passes character value of str[3]
function(st_var.str);       // passes the address of the string str

Here is anther example, passing the address of each member to a function:

function(&st_var.num);       // passes the address of the integer num
function(&st_var.ch);       // passes the address of the character ch
function(&st_var.str[3]);      // passes the address of the character str[3]
function(st_var.str);        // passes the address of the string str

In case, when a structure is used as an argument to a function, then the entire structure is passed using the normal call-by-value method. Here is an example demonstrating the concept of passing the entire structure to a function:

/* C Structures - This program simply demonstrates
 * the concept of passing the entire structure to 
 * a function in C language */
 
#include<stdio.h>
#include<conio.h>

struct st
{
	int num1;
	int num2;
	char ch;
	char name[20];
};

void fun(struct st stinf);

void main()
{
	struct st stoutf;
	clrscr();

	printf("Enter your name: ");
	gets(stoutf.name);
	printf("Enter any two numbers: ");
	scanf("%d%d", &stoutf.num1, &stoutf.num2);
	printf("Press y to see the sum..\n");
	fflush(stdin);
	scanf("%c", &stoutf.ch);
	if(stoutf.ch == 'y' || stoutf.ch == 'Y')
	{
		printf("\n");
		fun(stoutf);
		printf("\n\nPress any key to exit...\n");
		getch();
		exit(1);
	}

	getch();
}

void fun(struct st stinf)
{
	printf("%s, the sum of two number is %d", stinf.name, stinf.num1 + stinf.num2);
}

Here is the sample run of this C program:

c structure

Structure Pointers in C

In C language, you are free to use pointers to structures. Here is the general form to declare structure pointer in C:

struct st *st_pointer;

To find the address of any structure variable, then simply place the & operator before the structure's name. Let's look at this structure declaration:

struct stc
{
	int num;
	char ch;
	char str[20];
} stc_var;

struct stc *ptr;    // declared a structure pointer

now the following code fragment simply places the address of the structure stc_var into the pointer ptr:

ptr = &stc_var;

And to access the members of a structure using a pointer to that structure, then you must have to use the -> operator. Here is an example, referencing the num field:

ptr->num

Here is an example demonstrating the concept of structure pointers in C language:

/* C Structures - This program demonstrates
 * the concept of structure pointer in C */

#include<stdio.h>
#include<conio.h>

#define DELAY 128000
#define TEMP_DELAY 59

struct st_time
{
	int hours;
	int minutes;
	int seconds;
};

void display(struct st_time *time);
void update(struct st_time *time);
void delay(void);

void main()
{
	struct st_time systime;

	systime.hours = 0;
	systime.minutes = 0;
	systime.seconds = 0;

	for(;;)
	{
		update(&systime);
		display(&systime);
	}

	getch();
}

void update(struct st_time *time)
{
	time->seconds++;
	if(time->seconds == 60)
	{
		time->seconds = 0;
		time->minutes++;
	}

	if(time->minutes == 60)
	{
		time->minutes = 0;
		time->hours++;
	}

	if(time->hours == 24)
	{
		time->hours = 0;
	}

	delay();
}

void display(struct st_time *time)
{
	printf("%02d:", time->hours);
	printf("%02d:", time->minutes);
	printf("%02d\n", time->seconds);
}

void delay(void)
{
	long int time, temp;

	for(temp=0; temp<TEMP_DELAY; temp++)
	{
		for(time=1; time<DELAY; time++) ;
	}
}

Here is the sample run of this C program. This program continues displaying the time starting from 00:00:00

structures in c

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test