0% found this document useful (0 votes)
24 views21 pages

Introduction To C-Module 4 and 5 Notes

This document covers the concepts of strings, pointers, and structures in C programming. It explains how to declare, initialize, read, and write strings, as well as various string functions such as strcat, strcmp, and strcpy. Additionally, it introduces pointers, their declaration, and usage in memory management.

Uploaded by

rastudious001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views21 pages

Introduction To C-Module 4 and 5 Notes

This document covers the concepts of strings, pointers, and structures in C programming. It explains how to declare, initialize, read, and write strings, as well as various string functions such as strcat, strcmp, and strcpy. Additionally, it introduces pointers, their declaration, and usage in memory management.

Uploaded by

rastudious001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Module 4 and 5 (Strings, Pointers and Structures)

Strings
String variable:

A string is an array of characters. Any group of characters defined between double quotation
marks is called a constant string. String in C programming is a sequence of characters
terminated with a null character „\0‟. Strings are defined as an array of characters. The
difference between a character array and a string is the string is terminated with a unique
character „\0‟.
Example:
“Good Morning Everybody”
Character strings are often used to build meaningful and readable programs. A string variable
is any valid C variable name and is always declared as an array.

Declaring and initializing string variables:


The general form of string variable is
char string_name[size];
The size determines the number of characters in the string-name.
Some examples are:
char state[10];
char name[30];
When the compiler assigns a character string to a character array, it automatically supplies a
null character(„\0‟) at the end of the string.
Character arrays may be initialized when they are declared. C permits a character array to be
initialized in either of the following two forms:
char state[10]=” KARNATAKA”;
char state[10]={„K‟,‟A‟,‟R‟,‟N‟,‟A‟,‟T‟,‟A‟,‟K‟,‟A‟,‟\0‟};
The reason that state had to be 10 elements long is that the string KARNATAKA contains 10
characters and one element space is provided for the null terminator. C also permits us to
initialize a character array without specifying the number of elements.
For example, the statement
char string[ ] ={„H‟, „E‟, „L‟, „L‟, „O‟ ,‟\0‟};
Defines the array string as a six-element array.

Reading and writing strings:


To read a string of characters input function scanf can be used with %s format specification.
Example:
char add[20];
scanf(“%s”, add);
Note that unlike previous scanf calls, in the case of character arrays, the &(ampersand) is not
required before the variable name. The scanf function automatically terminates the string that is
read with a null character and therefore the character array should be large enough to hold the
input string plus the null character.

Program to read a series of words using scanf function


main()
{
char text1[50],text2[50],text3[50],text4[50];
printf(“Enter text:\n”);
scanf(“%s %s”, text1,text2);
scanf(“%s”, text3);
scanf(“%s”, text4);
printf(“\n”);
printf(“text1= %s\n text2=%s\n”, text1,text2);
printf(“text3= %s\n text4= %s\n”, text3,text4);
}

Writing strings:
The printf function with %s can be used to display an array of characters that is
terminated by the null character.
Example:
printf(“%s”, text);
Can be used to display the entire contents of the array name.

Using the puts( ) and gets( ) Functions:


The gets( ) function reads a string from keyboard. This function stops reading the string
only when we press the ENTER key from the keyboard. The gets( ) function is similar to the
scanf( ) function. The difference between the gets( ) and scanf( ) function is that the gets( )
function can read the whole sentence, which is a combination of multiple words; while the
scanf( ) function can read the character until a space or a newline character is encountered in a
sentence. The following program shows that the scanf( ) function cannot store the string data of
multiple words in a variable.
#include<stdio.h>
main( )
{
char msg[70];
printf(“enter the message”);
scanf(“%s”,msg);
printf(“%s”,msg);
}
Output:
enter the message
welcome to computer lab
welcome

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 2


In the above program, the scanf( ) function does not read multiple words into an array. This is
because when we enter a space after the word welcome, the scanf( ) function considers it as the
end of string and do not consider any character typed after it.
The gets ( ) function in place of scanf ( ) function is used to overcome this problem of reading
multiple words into an array.
The puts( )function, on the other hand, prints a string or a value stored in a variable to the
console in the next line. The following program shows the use of gets( ) and puts( ) functions.
#include<stdio.h>
#define length 100
main( )
{
char student_name1[length]=”John”;
char student_name2[length]=”Alex”;
puts(“Name of 1st student:”);
puts(student_name1);
puts(“Name of 2nd student:”);
puts(student_name2);
puts(“Enter a new name for the 2nd student”);
gets(student_name2);
puts(student_name1);
puts(student_name2);
}
Output:
Name of 1st student:
John
Name of 2nd student:
Alex
Enter a new name for the 2nd student
Marc
John
Marc
In the above program, the puts( ) function prints a string, Name of 1st student: to the console.
The value stored in the student_name1 array is printed by using the puts() function. Another
string, Name of 2nd student: is printed along with the value stored in the student_name2 array by
using the puts( ) function. The program prompts us to enter a new name for the 2nd student. The
entered value gets stored in the student_name2 array by using the gets( ) function. At the end, the
values stored in the student_name1 and student_name2, arrays are printed to the console.

String functions:
C library supports a large number of string functions. The list given below depicts the
string functions

Function Action
strcat( ) concatenates two strings
strcmp( ) compares two strings
strcpy( ) copies one string with another

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 3


strlen( ) finds the length of a string.
strupr( ) used to convert the letters of string to uppercase
strlwr( ) used to convert the letters of string to lowercase
strrev( ) used to reverse the string

String Concatenation :strcat( ) function:

The strcat function joins two strings together. The general form is

strcat(string1,string2);

string1 and string2 are character arrays. When the function strcat is executed. String2 is
appended to string1. It does so by removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
Example
#include<string.h>
int main()
{
char src[20]= “ before”;
char dest[20]= “after ”;
strcat(dest, src);
puts(dest);
return 0;
}
The output will be: after before

String comparison: strcmp( ) function:

The strcmp function compares two strings identified by the arguments and has a value 0
if they are equal.
The general form is :
strcmp(string1,string2);
String1 and string2 may be string variables or string constants.
On comparing the return value be determined basis the strings setup as shown below.
The function returns a definite value that may be either 0, >0, or <0. In this function, the two
values passed are treated as case sensitive means „A‟ and „a‟ are treated as different letters.
The values returned by the function are used as:
i) 0 is returned when two strings are the same
ii) If str1<str2 then a negative value is returned
iii) If str1>str2 then a positive value is returned
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]=”copy”;

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 4


char str2[]=”Trophy”;
int I,j,k;
i=strcmp(str1, “copy”);
j=strcmp(str1, str2);
k-strcmp(str1, “f”);
printf(“\n %d %d %d”,I,j,k);
return 0;
}
Output: 0 -1 1

String copying: strcpy( ) function:


The strcpy() function works almost like a string-assignment operator. The general format is
strcpy(string1,string2);
It copies the contents of string2 to string1. string2 may be a character variable or a string
constant.
Example:
#include<string.h>
int main()
{
char src[20]= “ Destination”;
char dest[20]= “”;
printf(“\n source string is = %s”, src);
printf(“\n destination string is = %s”, dest);
strcpy(dest, src);
printf (“\ntarget string after strcpy() = %s”, dest);
return 0;
}
Output
Source string is = Destination
Target string is =
Target string after strcpy() = Destination

Finding the length of a string: strlen( ) function:


This function counts and returns the number of characters in a string.
The general syntax is n=strlen(string);
Where n is an integer variable which receives the value of the length of the string. The
argument may be a string constant. The counting ends at the first null character.
Example:
#include<stdio.h>
int main()
{
int length;
char s[20] = “We are Here”;
length=strlen(s);
printf(“\Length of the string is = %d \n”, length);
return 0;

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 5


}
Length of the string is = 11

strlwr( )/ strupr( ) Functions:


Sometimes you may need to convert the lowercase letters of any string to the uppercase or
vice-versa. As it can be understood the lwr stands for lowercase and upr stands for uppercase.
For this purpose there are two direct string functions in C, they can be used to perform the
conversions either from upper to lower case or vice-versa. Here, we have explained an
example of the same:
#include<stdio.h>
#include<string.h>
int main()
{
char str[]=”CONVERT me To the Lower Case”;
printf(“%s\n”, strlwr(str));
return 0;
}
Output: convert me to the lower case
Similarly, if we will use the strupr function in place of strlwr, then all the content will be
converted to the upper case letters. We can use the strupr function, defined in the string
header file. Through this function, all letters of the string are converted, that too without any
long manual procedure.

Function strrev()
If you want to reverse any string without writing any huge or extensive program manually,
then you can use this function. The rev in the strrev() stands for reverse and it is used to
reverse the given string. Function strrev() is used to reverse the content of the string. Strrev
function is used to check the nature of the string, whether the given string is a palindrome or
not. Several other uses and applications are also present in the string reverse function. One of
its uses is given below:
#include<stdio.h>
#include<string.h>
int main()
{
char temp[20]=”Reverse”;
printf(“String before reversing is : %s\n”, temp);
printf(“String after strrev() :%s”, strrev(temp));
return 0;
}

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 6


Character functions in C
Character functions need ctype.h header file to be included in the program.
Different character functions provided by C Language are:
1. isalpha():
This function checks whether the character variable/constant contains alphabet or
not.
2. isdigit()
This function checks whether the character variable/ constant contains digit or not.
3. isalnum()
This function checks whether the character variable/constant contains an alphabet
or digit.
4. ispunct()
This function checks whether the character variable/constant contains a punctuator
or not. Punctuators are comma, semicolon etc.
5. isspace()
This function checks whether the character variable/constant contains a space or
not.
Program to demonstrate the use of character functions.
#include<ctype.h>
#include<stdio.h>
int main()
{
char n;
printf("\nEnter a character=");
n=getche();
if(isalpha(n))
printf("\nYou typed an alphabet");
if(isdigit(n))
printf("\nYou typed a digit");
if(isalnum(n))
printf("\nYou typed an alphabet or digit");
if(isspace(n))
printf("\nYou typed a blank space");
if(ispunct(n))
printf("\nYou typed punctuator");
return(0);
}

Output

Enter a character=A
You typed an alphabet

6. isupper()

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 7


This function checks whether the character variable/constant contains an capital
letter alphabet or not.
7. islower()
This function checks whether the character variable/constant contains a lowercase
alphabet or not.

8. toupper()
This function converts lowercase alphabet into uppercase alphabet.
9. tolower()
This function converts an uppercase alphabet into lowercase alphabet.
Program to use of islower,isupper,tolower(),toupper().
#include<ctype.h>
#include<stdio.h>
int main()
{
char n;
printf("\nEnter an alphabet=");
n=getche();
if(islower(n))
n=toupper(ch);
else
ch=tolower(ch);
printf("\nNow alphabet=%c",n);
return(0);
}

Output

Enter an alphabet=A
Now alphabet=a

Pointers:
Pointers in C are easy and fun to learn. Some C programming tasks are performed more
easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed
without using pointers. As we know, every variable is a memory location and every memory
location has its address defined which can be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following example, which will print the address of
the variables defined:
#include <stdio.h>

int main ()
{

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 8


int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

Address of var1 variable: bff5a400


Address of var2 variable: bff5a3f6

Basics of pointers:
A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location. In other words, a pointer is a variable that represent the location (rather
than the value) of a data item, such as a variable or an array element. It is a variable that holds a
memory address. This address is the location of another variable or an array element in memory.
For example, if one variable contains the address of another variable, the first variable is said to
point to the second.

Declaring Pointer Variables:


Like any variable or constant, we must declare a pointer before we can use it to store any
variable address. The general form of a pointer variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as
a pointer. Following are the valid pointer declaration:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.

For example: int *ptr;

In the above example, ptr is the name of our variable. The „*‟ informs the compiler that we want
a pointer variable. i.e. to set aside number of bytes required to store an address in memory. The

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 9


int says that we intend to use our pointer is said to “point to” an integer. However, note that
when we wrote int k; we did not give k a value. Similarly, ptr has no value, this means that we
haven‟t stored an address in it in the above declaration.

Initializing Pointer Variables:

The process of assigning the address of a variable to a pointer variable is known as


initialization of pointer variable.
Example: ptr=&k;
The & operator retrieves the address of k, even though k is on the right hand side of the
assignment operator = and copies that to the contents of our pointer ptr. Now ptr is said to
“point to” k. The only requirement here is that the variable k must be declared before the
initialization takes place. We must ensure that the pointer variables always point to the
corresponding type of data. Here are few examples:
int i, *p, *r; /* integer variable and pointer declarations */
float f, *q; /* float variable and pointer declarations */
p=&i; /* Correct initialization of integer pointer */
r=p; /* Correct initialization we can assign value of other pointer variable to pointer
variable */
q=&f; /* Correct initialization of float pointer */
p=&f; /* Incorrect initialization since data type does not match */
Pointer variables can point to numeric or character variable, arrays, functions or other pointer
variables. Thus a pointer variable can be assigned the address of an ordinary variable or it can be
assigned the value of other pointer variable provided both pointer variables are of same type.

Types of Pointer:
There are majorly four types of pointers, they are:
 Null Pointer
 Void Pointer
 Wild Pointer
 Dangling Pointer

Null Pointer:
A pointer can also be initialized by assigning a NULL value. It is always a good practice
to assign a NULL value to a pointer variable in case we do not have exact address to be assigned.
This is done at the time of variable declaration. A pointer that is assigned NULL is called
a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program:

#include <stdio.h>
int main ()
{

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 10


int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );

return 0;
}

When the above code is compiled and executed, it produces the following result:

The value of ptr is 0

Void Pointer:
When a pointer is declared with a void keyword, then it is called a void pointer. To print the
value of this pointer, you need to typecast it.
Syntax:
void *var;
Example:
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting, a = %d", *(int *)ptr);
return 0;
}

When the above code is compiled and executed, it produces the following result:

After Typecasting, a=2

Wild Pointer:
A wild pointer is only declared but not assigned an address of any variable. They are very tricky,
and they may cause segmentation errors.
Example:
#include<stdio.h>

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 11


int main()
{
int *ptr;
printf(“ptr=%d”,*ptr);
return 0;
}

When the above code is compiled and executed, it produces the following result:

Segmentation fault (core dumped)

Dangling Pointer
 Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this
memory, then this p is called a dangling pointer.
 You can deallocate a memory using a free() function.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=5;
ptr=&a;
free(ptr);
//now this ptr is known as dangling pointer.
printf(“After deallocating its memory *ptr=%d”,*ptr);
return 0;
}

When the above code is compiled and executed, it produces the following result:

*** Error in „./a.out‟: free( ): invalid pointer : 0x00007ffd808ceae4 ***


Aborted (core dumped)

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 12


Pointer Expressions:
In general, expressions involving pointers has same rules as other expressions.
Pointer Assignments:
We can use a pointer on the right-hand side of an assignment to assign its value to another
pointer.
Example:
/* Simple program illustrating pointer assignment */
#include<stdio.h>
main()
{
int var=50;
int *p1,*p2;
p1=&var;
p2=p1;
printf(“Values at p1 and p2 are : %d %d\n”,*p1,*p2); /* print the value of var twice */
printf(“Address pointed by p1 and p2 are : %p %p”, p1, p2); /*print the address of var twice */
}
Output:
Value at p1 and p2 are: 50 50
Address pointed by p1 and p2 are: 0052FAD0 0052FAD0
After two assignment statements: p1=&var and p1=p1, p1 and p2 both point to variable var.
Thus, both p1and p2 refer to the same object. It is important to note that the addresses are
displayed by using the %p printf() format specifier, which causes printf( ) to display an address
in the format used by the host computer.

Scansets in C
scanf family functions support scanset specifiers which are represented by %[]. Inside scanset,
we can specify single character or range of characters. While processing scanset, scanf will
process only those characters which are part of scanset. We can define scanset by putting
characters inside square brackets. Please note that the scansets are case-sensitive.
We can also use scanset by providing comma in between the character you want to add.
example: scanf(%s[A-Z,_,a,b,c]s,str);
This will scan all the specified character in the scanset.
Let us see with example. Below example will store only capital letters to character array 'str',
any other character will not be stored inside character array.

/* A simple scanset example */


#include <stdio.h>

int main(void)
{
char str[128];

printf("Enter a string: ");


scanf("%[A-Z]s", str);

printf("You entered: %s\n", str);

return 0;
}
Output:
Enter a string: GEEKs_for_geeks
You entered: GEEK

If first character of scanset is '^', then the specifier will stop reading after first occurrence of
that character. For example, given below scanset will read all characters but stops after first
occurrence of 'o'.
scanf("%[^o]s", str);
Let us see another example:
/* Another scanset example with ^ */
#include <stdio.h>

int main(void)
{
char str[128];

printf("Enter a string: ");


scanf("%[^o]s", str);

printf("You entered: %s\n", str);

return 0;
}
Output:
Enter a string: http://geeks for geeks
You entered: http://geeks f

Review Questions
1. What is string? How is it declared and initialized? (5 Marks)
2. Explain the functions used to read strings with examples. (5 Marks)
3. Explain the functions used to display string on screen with examples. (5 Marks)
4. List the most used string handling functions and explain their usage. (8 Marks)
5. Explain the character functions in C with examples. (8 Marks)
6. Write a C program to check the given string is palindrome or not. (6 Marks)
7. Write a C program to count the number of vowels and consonants in a given string. (imp)
8. What is pointer? What is its purpose? (4 Marks)
9. How is pointer variable declared in C? (4 Marks)
10. Explain the process of initialization of pointer variable. (4 Marks)
11. Write a short note on operations on pointers. (4 Marks)
12. What do you mean pointer to pointer? Explain. (4 Marks)
13. Write a note on arrays and pointers. (4 Marks)
14. Write a C program to find sum, mean and standard deviation of array elements using
pointer. (8 Marks)
15. Explain scanset in C language.
Structure in C

C arrays allow us to define type of variables that can hold several data items of the same kind
but structure is another user defined data type available in C programming, which allows us
to combine data items of different kinds.
Defining a Structure:
Structure is the collection of variables of different types under a single name for better handling.
For example: we want to store the information about person about his/her name, citizenship
number and salary. We can create these information separately but, better approach will be
collection of these information under single name because all these information are related to
person.
In C, a structure is a derived data type consisting of a collection of member elements and their
data types. Thus, a variable of a structure type is the name of a group of one or more members
which may or may not be of the same data type. In programming terminology, a structure data
type is referred to as a record data type and the members are called fields.
Keyword struct is used for creating a structure.
Syntax of structure:
struct structure_name
{
data_type member1;
data_type member2;
….
data_type memeber;
};
We can create the structure for a person as mentioned above as:
struct person
{
char name[50];
int cit_no;
float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration:
When a structure is defined, it creates a user -defined type but, no storage is allocated.
For the above structure of person, variable can be declared as:
struct person
{
char name[50];
int cit_no;
float salary;
};
Inside main function:
struct person p1, p2, p[20];
Another way of creating sturcture variable is:
struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct
person are created.
Accessing members of a structure
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)
Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary
Example of structure
Write a C program to add two complex numbers using structure.
#include <stdio.h>
struct complex {
float real;
float imag;
};

void main()
{
struct complex n1,n2,sum;
printf("For 1st complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n1.real, &n1.imag);
printf("\nFor 2nd complex number \n");
printf("Enter the real and imaginary parts: ");
scanf("%f %f", &n2.real, &n2.imag);
sum.real=n1.real+n2.real;
sum.imag=n1.imag+n2.imag;
printf("Sum = %.1f + %.1fi", sum.real, sum.imag);
}

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 2


C Structure Initialization:
When we declare a structure, memory is not allocated for un-initialized variable. We can
initialize structure variable in different ways -
Way 1: Declare and Initialize
struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration
we have initialized the structure variable.

std1 = { "Pritesh",67,78.3 }

This is the code for initializing structure variable in C programming

Way 2 : Declaring and Initializing Multiple Variables


struct student
{
char name[20];
int roll;
float marks;
}

std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
In this example, we have declared two structure variables in above code. After declaration of
variable we have initialized two variable.

std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};

Way 3 : Initializing Single member


struct student
{
int mark1;
int mark2;

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 3


int mark3;
} sub1={67};
Though there are three members of structure, only one is initialized, and then remaining two
members are initialized with Zero. If there are variables of other data type then their initial
values will be -

Data Type Default value if not initialized

integer 0

float 0.00

char NULL

Way 4: Initializing inside main


struct student
{
int mark1;
int mark2;
int mark3;
};

void main()
{
struct student s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won‟t be allocated for the structure. i.e only writing
below declaration statement will never allocate memory

struct student
{
int mark1;
int mark2;
int mark3;
};

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 4


We need to initialize structure variable to allocate some memory to the structure.

struct student s1 = {89,54,65};

Accessing and Processing a Structure:


The members of structure can be accessed and processed as separate entities. A structure
members can be accessed by using dot (.) also called period operator. The syntax is
Variable.member
Where Variable refers to the name of a structure type variable and member refers to the name of
a member within the structure.
The following program demonstrate the accessing of structure.
/* Simple program to demonstrate the accessing of structure */
#include<stdio.h>
#include<string.h>
struct date
{
int day;
int year;
char month_name[10];
};
main()
{
struct date d;
d.day=25;
strcpy(d.month_name,”January”);
d.year=2006;
printf(“Day=%d Month=%s Year=%d\n”, d.day, d.month_name, d.year);
}
Output:
Day=25 Month=January Year=2006

Array of Structures:
When we are working with a group of entities and their attributes, we need to create array
of structures. C Structure is collection of different data types (variables) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is also called as
structure array in C.
For example, if we want to work with students data base we can create a structure student, in
which we can store the information about the address, age, marks obtained by ther student and so
on. By creating an array of structure student we can store information of group of students. Then
by accessing aray of structure student we can quickly and easily work with student‟s
information.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 5


The following figure shows the array of structure student. It can store information of 40 student
in the class.
Field 1 Field 2 Field 3 Field 4

Student A[0]

Student A[1]

Student A[39]

Structure is used to store the information of One particular object but if we need to store such
100 objects then Array of Structure is used.

Example :

struct Bookinfo
{
char bname[20];
int pages;
int price;
}Book[100];

Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is used.
3. b1[0] stores the Information of 1st Book , b1[1] stores the information of 2nd Book and So
on We can store the information of 100 books.
Accessing Pages field of Second Book :

Book[1].pages

Example program for array of structures in C:


Implement structures to read, write and compute average marks and the students scoring above
and below average marks for class of N students.

Notes Prepared by Sayeesh, Dept. of CSE, YIT Page 6


Review Questions
1. What is a structure? How does a structure differ from an array? (4 Marks)
2. What is a structure member? What is a relationship between a structure member and a
structure? (4 Marks)
3. Describe the syntax of defining a composition of structure. (4 Marks)
4. How can structure variables be declared? How do structure variable declarations differ
from structure type declarations? (5 Marks)
5. How is structure initialized? (4 Marks)
6. How is an array of structures initialized? (5 Marks)
7. How is a structure member accessed? (4 Marks)
8. Write note on: i) Arrays within structures ii) Arrays of structures. (4 Marks)
9. How can a structure member be processed? (4 Marks)
10. What is nested structure? Explain with example. (6 Marks)

You might also like