PPS Unit 2 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

UNIT-II

Arrays - One-dimensional Arrays, two-dimensional arrays, multidimensional arrays.


Strings - Concepts, C Strings, String Input / Output functions, arrays of strings, string
manipulation functions, string / data conversion.
Structures and unions- Declaration, definition and initialization of structures, accessing
structures, nested structures, arrays of structures, unions, typedef.
Pointers- Introduction, pointers to pointers, pointer operations, array of pointers, pointer to
void, pointers to arrays, pointers to structures, self referential structures

ARRAYS
1.One Dimensional Array in C

 An array is defined as the collection of similar type of data items stored at contiguous
memory locations.
 Arrays are the derived data type in C which can store the primitive type of data such
as int, char, double, float, etc.
 Arrays can be randomly accessed by using its index number.
Properties of Array:
o Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically.
Declaration of C Array
data_type array_name[array_size];
Ex:- int marks[5];
Initialization of C Array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

array example:
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Output:
80
60
70
85
75
Array: Declaration with Initialization

int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size.
So it may also be written as the following code.
int marks[]={20,30,40,50,60};
C program to declare and initialize the array in C.
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
return 0;
}
Output:
20
30
40
50
60

2.Two-Dimensional Array in C

The two-dimensional array can be defined as an array of arrays.


The 2D array is organized as matrices which can be represented as the collection of rows and
columns.
Declaration of two dimensional Array in C

data_type array_name[rows][columns];
Ex:- int arr[4][3];
Initialization of 2D Array in C:
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}

Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
2D array example: Storing elements in a matrix and printing it.
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30

Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78

Passing array to a function:


#include <stdio.h>
void getarray(int arr[])
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}
Output:
Elements of array are: 45 67 34 78 90

Passing array to a function as a pointer:


#include <stdio.h>
void printarray(char *arr)
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%c ", arr[i]);
}
}
int main()
{
char arr[5]={'A','B','C','D','E'};
printarray(arr);
return 0;
}

Output:
Elements of array are : A B C D E
20
30

Strings
A string is an array of characters that is terminated by a NULL character ‘\0’.
It can be read as a single entity, unlike other types of arrays.
Declaration:
char String_name[size_of_the_string];
Example:
char name[15];
Initialization:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";

char ch[ ] = { 'a', 'e', 'i', 'o', 'u', '\0'};


Here the characters a, e, i, o, u are stored character by character in the character array ch.
In this, the NULL ('\0') character can be added by the user at the end of the initialization as
the array is initialized with values character by character
The one-dimensional character array can also be written as char ch[ ] = "aeiou";
Here double quotes are used to mention the string constant.
In this type of initialization the NULL ('\0') character is automatically appended.
Let us consider another example: char text[4] = "COLLEGE";.
In this example only the first 4 characters of the string COLLEGE are assigned to the array
and NULL is not included.
The output may contain unexpected characters after the first four characters
COLL.
Hence, care must be taken to mention the size of the array and that is large enough to
store all the characters including NULL.
So we can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};

String I/O

The syntax of gets() function is


char * gets(char *str);

Read using scanf() and gets() a NULL ('\0') is automatically inserted at the end of the string.
Reads a string using gets() until it encounters a newline or EOF. ‘\n’ is replaced by the ’\0’ at
the end of the string.

code:
char str[50];
printf(“\nEnter a string use gets”);
gets(str);
printf(“\nString is:%s”,str);

output
Enter a string use gets:KMIT is autonomous college
String is:KMIT is autonomous college
---------------------------------------------------------
Syntax of puts
int puts(char *str)

puts() is used to display the string on the console. The delimiter character ‘\0’ of the string is
automatically converted into a newline character ‘\n’ when the string is displayed.

code:
char str[50];
puts(“Give your college name”);
gets(str);
puts(“COLLEGE NAME”);
puts(str);

output
Give your college name
KMIT Autonomous
COLLEGE NAME
KMIT Autonomous
---------------------------------------------
Reading and displaying a string using scanf() and printf():

scanf() function can be used to read a string by using %s.


Reads a string until it encounters a whitespace character and a NULL ('\0') is added to the
string.
syntax of reading a string
char char[25];
scanf("%s", chArr);
Here & is not used with variable as chArr itself represents the base address of the array.
The function printf() is used with format specifier %s to display the string.
The syntax of displaying a string with printf() is
printf("%s", chArr);
Here the string value that is stored in chArr is displayed.

Reading a string using getchar():

Alternative to read a string is read character by character.


Characters are read one at a time using getchar() (or) scanf() with %c.
The NULL ('\0') character is not appended, if it is read character by character.
It is necessary to add it in a separate statement.

int getchar(void);

To read a string character by character using getchar() function.


void main() {
char ch[100]; int i = 0;
printf("Enter a string (Read up to # is given) : ");
while ((ch[i] = getchar()) != '#') { i++; }
ch[i] = '\0';
printf("\nThe given string is : ");
puts(ch);
}
Output
Enter a string (Read up to # is given) :KMIT College#
The given string is: KMIT College
----------------------------------------------------------------------
Above code, getchar() reads character from the keyboard and stored in ith location of array
ch.
Next, it checks whether the given character is '#' or not, if it is not, and repeat the loop again.
While loop is repeated until user enters character '#'.
If '#' is given it is stored at the end of that string.
The statement ch[i]='\0'; stores the NULL character at where '#' is stored.

putchar():
C library function int putchar(int char) writes a character specified by the argument char to
stdout.
int putchar(int char)

#include <stdio.h>
int main () {
char ch;
for(ch = 'A' ; ch <= 'Z' ; ch++)
{
putchar(ch);
}
return(0);
}
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ

String Manipulation Functions:


In C, we have different types of string manipulation functions which are used for the
different string operations.
C supports a string handling library which provides useful functions that can be used for
string manipulations.
All these string handling functions are defined in the header file string.h.
string.h header file must be included to use the string functions
Major string handling functions used are tabulated below.
String functions Description

size_t strlen(const Computes the length of the string str up to but not including the
char *str) terminating null character

char *strcpy(char
*dest, const char Copies the string pointed to, by src to dest.
*src)

char *strcat(char Appends the string pointed to, by src to the end of the string pointed to
*dest, const char
*src) by dest.

Compares the string pointed to, by str1 to the string pointed to by str2.
int strcmp(const char
*str1, const char Returns 0 if str1 is same as str2. Returns <0 if strl < str2.
*str2) Returns >0 if str1 > str2
char *strlwr(char Returns the modified string obtained after converting the characters
*str) of the given string str to lowercase

char *strupr(char Returns the modified string obtained after converting the characters
*str) of the given string str to uppercase

char *strchr(const
char *str, int c) Returns pointer to first occurrence of c in str

char *strstr (const


char *s1, const char
*s2); Returns pointer to first occurrence of s2 in s1

char *strrev(char
Returns the string after reversing the given string str
*str)

char *strncpy(char
Copies up to n characters from the
*dest, const char
string pointed to, by src to dest.
*src, size_t n)

char*strncat(char Appends the string pointed to, by src to the end of the string pointed
*dest, const char to,
*src, size_t n) by dest up to n characters long.

int strcmpi ( const Same as strcmp() function. But, this function negotiates case. “A” and
char * str1, const
char * str2) “a” are treated as same.

strlen():
• The function strlen() is used to find the length of a
given string. This function returns only integer data (or) numeric data.
• The format of strlen() is integer_variable = strlen(string);.

int main() {
int len1, len2;
//initializing the strings
char string1[] = "Hello";
char string2[] = {'c','o','m','p','u','t','e','r','\0'};
//calculating the length of the two strings
len1 = strlen(string1);
len2 = strlen(string2);
//displaying the values
printf("Length of string1 is: %d \n", len1);
printf("Length of string2 is: %d \n", len2);
}
Output:

Length of string1 is: 5


Length of string2 is: 8
========================
strcpy():
The function strcpy() is used to copyone string into another string including the NULL
character (terminator char ‘\0’).
The format of strcpy( ) is strcpy(string1, string2);.

strncpy()
char *strncpy( char *str1, char *str2, size_t n) size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends
several terminator chars(‘\0’) to accumulate the length of str1 to make it n.

code
int main() {
//initializing the strings
char string1[] = "Hello“,str2[15],str3[15];
strcpy(str2,string1);
strncpy(str3,string1,2);

//displaying the values


printf("string2 is: %s \n",str2);
printf(“string3 is: %s \n", str3);
}
Output
string2 is: Hello
strin3 is: st
================
strcmp():
The function strcmp() is used for comparison of two strings and it always returns
numeric data.
The syntax of strcmp() is variable = strcmp (string1, string2);,
where string1, string2 are two strings and variable is of the type integer.
The comparison of two strings is dependent on the alphabets and not on the size of
the strings.
• If the function strcmp() returns zero, both strings are equal.
• If the function returns less than zero, string2 is higher than string1.
• If the function returns greater than zero, string1 is higher than string2.

strcmpi(): is one of the inbuilt string function in c programming which is used to compare
two strings without any discrimination between uppercase and lowercase letters, if the strings
are same, it returns 0. Otherwise it returns a nonzero value.

int i;
char str1[15]=”Good”,str2[15]=”good”;
printf(“String1:%s\nString2:%s”,str1,str2);
i=strcmp(str1,str2);
puts(“Comparing strcmp function”);
if(i==0)
printf("The strings are equal");
else
printf("The strings are not equal");
i=strcmpi(str1,str2);
puts(“Comparing strcmpi function”);
if(i==0)
printf("The strings are equal");
else
printf("The strings are not equal");

Output
String1:Good
String2:good
Comparing strcmp function
The strings are not equal
Comparing strcmpi function
The strings are equal

===================================
strcat():
• The function strcat() is used to concatenate two strings into one string
• The syntax of strcat() is strcat(string1, string2); where string1, string2 are two
different strings. Here string2 is concatenated with string1, and finally the resultant
concatenated string is stored in string1.
strncat():
char *strncat(char *str1, char *str2, int n)
It concatenates n characters of str2 to string str1. A terminator char (‘\0’) wil always be
appended at the end of the concatenated string.
char str1[15]=”Good”,str2[15]=”Morning”;
char str3[15];
strcpy(str3,str1);
strcat(str1,str2);
strncat(str3,str2,4);
printf("The string after strcat 4 chars is %s",str1);
printf("\nThe string after strncat 4 chars is %s",str3);

Output
The string after strcat is GoodMorning
The string after strncat 4 chars is GoodMorn

===================

strstr
char *strstr(char *str, char *srch_term)
it searches for string srch_term in string str.
• This function returns a pointer to the first occurrence in haystack of any of the entire
sequence of characters specified in needle, or a null pointer if the sequence is not present in
haystack.
#include <stdio.h>
#include <string.h>
int main () {
char mnStr[20] = "CSE Dept";
char substr[10] = "Dept";
char *ret;
ret = strstr(mnstr, substr);
printf("The substring is: %s\n", ret);
return(0);
}
Output
The substring is: Dept
===============================
strlwr( ): converts string to lowercase
strupr( ): converts string to uppercase

char str1[15]=”Good”,str2[15]=”Morning”;
char str3[15];
strlwr(str1);
strupr(str2);

printf(“Lower case: %s",str1);


printf(“Upper case: %s",str2);

Output:
Lower case: good
Upper case: MORNING

================================
strrev( ): reverse of give string
printf("Enter string ");
gets(str1);
strrev(str1);
printf("Reverse string is");
printf("%s",str1);
Output
Enter string Good Morning
Reverse string is gninroM dog
================================
Array of Strings:
An array of strings is a two-dimensional character array.
The size of the first index (rows) determines the number of strings and the size of the
second index (columns) determines maximum length of each string.
The syntax of declaring an array of strings is:
char array_name[row_size][column_size];
Let us consider an example:
char str[4][7] = {"First", "Second", "Third", "Four" };

char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};

#include<stdio.h>
int main()
{
int i;
char ch_arr[3][10] = { "Spike","Tom","Jerry"
};
puts(“Array of strings”);
for(i = 0; i < 3; i++)
{
printf("string%d = %s \n", i+1, ch_arr [i]);
}
return 0;
}
Output
Array of strings
Spike
Tom
Jerry
String/Data Conversion

Syntax
int atoi(const char *string)

The stdlib.h library must be included for the atoi() function to be executed
#include<stdio.h>
#include <stdlib.h>

int main() {
char str[10] = "122";
char str2[10] = "Hello!";
char str3[10] = "99Hello!";
int x = atoi(str); // Converting a numeric string
printf("Converting '122': %d\n", x);

x = atoi(str2); // Converting an alphanumeric string


printf("Converting 'Hello!': %d\n", x);

x = atoi(str3); // Converting a partial string


printf("Converting '99Hello!': %d\n", x);
return 0;
}
Output
Converting '122': 122
Converting 'Hello!': 0
Converting '99Hello!': 99

strtol() – a string conversion function that converts a sequence of character representing an


integer into long int.
long strtol( const char *sPtr, char **endPtr, int base );
sPtr = string representing an integer number
endPtr = pointer set by the function to the next character in sPtr after integer value
base = base of the value being converted
#include<stdio.h>
#include<stdlib.h>
int main()
{
//initializing string pointer
const char *sPtr = "423 student are pass";
long n; //variable to store converted sequence
char *endPtr; //char type pointer
n = strtol( sPtr, &endPtr, 0 );
printf("Original String: \"%s\"\n", sPtr);
printf("\nLong int Value: %ld\nRemaining string part: %s\n", n, endPtr);
return 0;
}

the long int value converted from the string is stored in n whereas, the remaining part of the
string is assigned to endPtr.
The base value 0 indicates that the converted value can be in the following format:
octal format = base 8
decimal format = base 10
hexadecimal format = base 16

40
50
60

STRUCTURES
A Structure is a collection of elements of dissimilar data types. Structures provide the ability
to create user defined data types and also to represent real world data.

Suppose if we want to store the information about a book, we need to store its name (String),
its price (float) and number of pages in it (int). We have to store the above three items as a
group then we can use a structure variable which collectively store the information as a book.
Structures can be used to store the real world data like employee, student, person etc.

Declaration:
The declaration of the Structure starts with a Key Word called struct and ends with
semicolon. The Structure elements can be any built in types.

struct <Structure name>


{
Structure element 1;
Structure element 2;
-
-
-
Structure element n;
};

Then the Structure Variables are declared as


struct < Structure name > <Var1,Var2>;

Eg:-
struct emp
{
int empno.
char ename[20];
float sal;
};
struct emp e1,e2,e3;

The above Structure can also be declared as :

struct emp
{
int empno;
char ename[20];
float sal;
}e1,e2,e3;

Initialization:

Structure Variables can also be initialised where they are declared.

struct emp
{
int empno; char ename[20]; float sal;
};
struct emp e1 = { 123,”Kumar”,5000.00};

To access the Structure elements we use the dot (.) operator.


To refer empno we should use e1.empno
To refer sal we would use e1.sal

Structure elements are stored in contiguous memory locations as shown below. The above
Structure occupies totally 26 bytes.

e1.empno E1.ename E1.sal


123 Kumar 5000.00
2000 2002 2022
/* Program to illustrate the usage of a Structure.*/
main()
{
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e;

printf (“ Enter Employee number: \n”);


scanf(“%d”,&e.empno);
printf (“ Enter Employee Name: \n”);
scanf(“%s”,&e.empname);
printf (“ Enter the Salary: \n”);
scanf(“%f”,&e.sal);
printf (“ Employee No = %d”, e.empno);
printf (“\n Emp Name = %s”, e.empname);
printf (“\n Salary = %f”, e.sal);
}

NESTING OF STRUCTURES:
One Structure can be enclosed in another Structure. The Structure which is to be nested must
be declared before it is used. We can nest a Structure within a Structure, which is in still
another Structure and so on. Nesting of Structure can be done to any number of levels. The
elements of the nested Structure are accessed by using one more dot (.) operator.

Eg:-
struct date
{
int dd, mm, yy;
};
struct student
{
int rno;
char sname[15];
struct date dob;
};
struct student s;

Here, dob is the Nested Structure. To access this we use s.dob.dd or s.dob.mm or s.dob.yy.

/* Program to read Student Details and Calculate total and average using structures */

#include<stdio.h>
main()
{
struct stud
{
int rno;
char sname[20];
int m1,m2,m3;
};
struct stud s; int tot;

float avg;
printf(“Enter the student roll number: \n”);
scanf(“%d”,&s.rno);

printf(“Enter the student name: \n”);


scanf(“%s”,&s.sname);
printf(“Enter the three subjects marks: \n”);
scanf(“%d%d%d”,&s.m1,&s.m2,&s.m3);
tot = s.m1 + s.m2 +s.m3; avg = tot/3.0;
printf(“Roll Number : %d\n”,s.rno); printf(“Student Name: %s\n”,s.sname);
printf(“Total Marks : %d\n”,tot); printf(“Average : %f\n”,avg);
}
/* Program to read Item Details and Calculate Total Amount of Items*/

#include<stdio.h>
main()
{
struct item
{
int itemno;
char itemname[20];
float rate;
int qty;
};
struct item i;
float tot_amt;
printf(“Enter the Item Number \n”);
scanf(“%d”,&i.itemno);
printf(“Enter the Item Name \n”);
scanf(“%s”,&i.itemname);
printf(“Enter the Rate of the Item \n”);
scanf(“%f”,&i.rate);
printf(“Enter the number of %s purchased ”,i.itemname);
scanf(“%d”,&i.qty);
tot_amt = i.rate * i.qty;
printf(“Item Number: %d\n”,i.itemno);
printf(“Item Name: %s\n”,i.itemname);
printf(“Rate: %f\n”,i.rate);
printf(“Number of Items: %d\n”,i.qty);
printf(“Total Amount: %f”,tot_amt);
}

/*Program to illustrate the use of Nested Structures */

#include<stdio.h>
main()
{
struct date
{
int dd, mm, yy;
};
struct stud
{
int rno;
char sname[15];
struct date dob;
int tot;
};
struct stud s;

printf(“Enter the student roll number: \n”);


scanf(“%d”,&s.rno);

printf(“Enter the student name: \n”);


scanf(“%s”,&s.sname);

printf(“Enter the date of birth of student(dd/mm/yy): \n”);


scanf(“%d%d%d”,&s.dob.dd,&s.dob.mm,&s.dob.yy);

printf(“Roll Number : %d\n”,s.rno);


printf(“Student Name: %s\n”,s.sname);

printf(“Date of Birth: %d/%d/%d\n”, s.dob.dd, s.dob.mm, s.dob.yy);


printf(“Total Marks : %f\n”,s.tot);
}

ARRAYS OF STRUCTURES:
To store more number of Structures, we can use array of Structures. In array of Structures all
elements of the array are stored in adjacent memory location.
/* Program to illustrate the usage of array of Structures.

main()
{
struct book
{
char name[20];
float price;
int pages;
};
struct book b[10];

int i;

for (i=0;i<10;i++)
{
print(“\n Enter Name, Price and Pages”);
scanf(“%s%f%d”, b[i].name,&b[i].price,&b[i].pages);
}

for (i i=0;i<10;i++)
printf(“ \n%s%f%d”, b[i].name,b[i].price,b[i].pages);
}

STRUCTURES WITH FUNCTIONS:


The entire Structure can be passed to a function at once. Whenever a Structure is passed to a
function the Structure should be declared outside the main(), otherwise it will not be known
to all the functions in the program.

/*Program to illustrate the use of Structures with functions.*/


struct stud
{
int rno;
char name[20]; int
tot;
};
main()
{
struct stud s = { 111, “Ramoo”,500};
display(s);
}
display(struct stud s)
{
printf(“Roll Number: %d\n”, s.rno);
printf(“Student Name: %s\n”, s.name);
printf(“Total Marks: %d\n”, s.tot);
}

STRUCTURE POINTER:
A Pointer pointing to a struct is called Structure Poniter. A Structure Pointer can be used to
store the address of a Structure Variable. An arrow operator ( ) is used to refer the Structure
elements when a pointer is used with a Structure.

/* Program to illustrate the usage of Structures with Pointer */


struct emp
{
int empno;
char ename[20];
float sal;

};

main()
{
struct emp e;
reademp(&e);
displayemp(&e);
}

reademp(struct emp *e)


{
printf(“Enter Emp Details:”);

scanf(“\n%d%s%f”, &e empno, e ename, &e sal);


}

display emp(struct emp *e)


{
printf(“empno:%d\tename:%s\tSalary=%f”,e empno, ename,e sal);

SELF REFERENTIAL STRUCTURES:

A Self referential Structure is one that includes within its structure at least one member which
is a pointer to the same structure type. With self referential structures we can create very
useful data structures such as linked lists, trees etc.

Ex:
Struct tag
{
char name[40];
struct emp*next;
};

A structure contains two members a 40 element character array called name,and a pointer to
another structure of the same called next.

APPLICATIONS OF STRUCTURES:

Structures can be used for a Variety of Applications like:


a) Database Management.
(To maintain data about employees in an organisation, book in a library,
items in a Store etc)
b) Changing the size of the Cursor.
c) Clearing the contents of the Screen.
d) Placing the Cursor at appropriate position on Screen.

e) Drawing any graphics Shape on the Screen.


f) Receiving a Key from the Keyboard.
g) Checking the memory size of the Computer.
h) Finding the list of equipment attached to the Computer.
i) Formatting a Floppy.
j) Hiding a file from the Directory.
k) Displaying the Directory of a Disk.
l) Sending the Output to Printer.
m) Interacting with the Mouse.

UNIONS:
Union, similar to Structures, are collection of elements of different data types. However, the
members within a union all share the same storage area within the computer’s memory, here
as each member within a Structure is assigned its own unique Storage area.

Structure enables us to treat a member of different variables stored at different places in


memory; a union enables us to treat the same space in memory as a number of different
variables. That is, a union offers a way for a section of memory to be treated as a variable of
one type on one occasion and as a different variable of a different type on another occasion.

Unions are used to conserve memory. Unions are useful for applications involving multiple
members, where values need not be assigned to all of the members at any given time. An
attempt to access the wrong type of information will produce meaningless results.
The union elements are accessed exactly the same way in which the structure elements are
accessed using dot (.) operator.
The difference between the structure and union in the memory representation is as follows.
struct cx
{
int i;
char ch[2];
};
struct cx s1;

The Variable s1 will occupy 4 bytes in memory and is represented as

<----------- s.i -----------> s.ch[0] s.ch[1]

4002 4003 4004 4005


The above datatype, if declared as union then

union ex
{
int i;
char ch[2];
}
union ex u;

u.ch[0] u.ch[1]
<----------- s.i ----------->

4002 4003

/* Program to illustrate the use of unions */


main()
{
union example
{
int i;
char ch[2];
};
union example u;

u.i = 412;
print(“\n u.i = %d”,u.i);
print(“\n u.ch[0] = %d”,u.ch[0]);
print(“\n u.ch[1] = %d”,u.ch[1]);

u.ch[0] = 50; /* Assign a new value */


print(“\n\n u.i = %d”,u.i);

print(“\n u.ch[0] = %d”,u.ch[0]);


print(“\n u.ch[1] = %d”,u.ch[1]);
}
Output:
u.i = 412
u.ch[0] = 0
u.ch[1] =2

u.i = 562
u.ch[0] = 50
u.ch[1] =2

A union may be a member of a structure, and a structure may be a member of a union. And
also structures and unions may be freely mixed with arrays.

/* Program to illustrate union with in a Structure */


main()
{
union id
{
char
color;
int
size;
};
struct
{
char
supplier[20];
float cost;
union id desc;

}pant, shirt;

printf(“%d\n”, sizeof(union id));

shirt.desc.color = ‘w’;
printf(“%c %d\n”, shirt.desc.color, shirt.desc.size);
shirt.desc.size = 12;
printf(“%c %d\n”, shirt.desc.color, shirt.desc.size);

/* Program to raise a number to a power */


#include <stdio.h>
#include <math.h>

typedef union
{
float fexp; /* float exponent */
int nexp; /* integer exponent */
}nvals;

typedef struct
{
float x; /* value to raised to a power */
char flag; /* ‘f’ if exponent is float ‘i’ if exponent is integer */
nvals exp; /* union containing exponent */
}values;

float power (values a )/* function calculations power */


{
int i;
float y = a.x;

if (a.flag = = ‘i’)
{
/* integer exponent */
if (a.exp.nexp = = 0) /* zero exponent*/
y = 1.0;
else
{
for (i = 1;i<abs(a.exp.nexp);++i)
y * = a.x;
if (a.exp.nexp<0)
y = 1.0/y; /* negative integer exponent */
}
}
else
y = exp(a.exp.fexp*log(a.x)); /* floating point exponent */

return(y);
}

main()
{

values a ;
int i;
float n,y;

printf(“Enter the value for X”);


scanf(“%f”,&a.x);

printf(“Enter the value for n”);


scanf(“%f”,&n);

/* determine type of exponent */


i = (int)n;
a.flag = (i = = n) ? ‘i’ : ‘f’ 3

if((a.flag = = ‘i’)
a.exp.nexp = i;
else
a.exp.fexp = n;
/* raise X to the power */

if(a.flag = = ‘f’ && a.x <= 0.0)


printf(“ERROR, can’t raise negative no to floating point power”);
else
{
y = power(a);
printf(“\n y = % .4f”,y);
}
}

TYPEDEF:
typedef is used to create new datatype. The statement typedef is used while defining the new
data type.
Syntax:
typedef type dataname;
Here, type is the data type and dataname is the user defined name for that type.
typedef int hours;

Here, hours is another name for int and now we can use hours instead of int in the program as
follows:
/* Example to demonstrate typedefinition */
#define H 60
main()
{
typedef int hours;
hours hrs;
clrscr();

printf(“Enter hours\n”);
scanf(“%d”,&hrs);

printf(“minutes=%d”,hrs*H);
printf(“\nseconds=%d”,hrs*H*H);
}
Output:
Enter hours: 2
Minutes=120
Seconds=7200
Explanation of program: In the above example with typedef we had declared hours as an
integer data type. Immediately after the typedef statement hrs is a variable of hours datatype
which is similar to int. further the program calculates minutes and seconds using hrs variable.
20
30
40
50
60

Pointers
When we declare a variable, the compiler allocates required memory with specified name.
Pointer is a special type of variable used to store the memory location address of a variable.
Every pointer stores the address of variable with same datatype only.
For declaring a pointer variable: datatype *pointer_name;
Example: int *ptr;
Reference (address of) operator ‘&’ is used to access address of a variable.
Initialising a pointer
pointer_name = &varaible_name;
Example:
int a, *ptr;
a = 10;
ptr = &a;
Pointer can be used to access value at the address with the use of ‘*’ in front of pointer
variable name. Memory allocation of pointer variable:
• In computer, memory address of any memory location is an unsigned integer value,
which requires 2 bytes of memory in C.
• So, irrespective of pointer datatype every pointer variable is allocated with 2 bytes of
memory.
Can a pointer variable store a constant value? Yes (observe the below example)
Example: Program to initialize and access pointers
#include<stdio.h>
#define max 10
void main()
{
int a=10;
int *ptr1, *ptr2;
printf("a=%d\n",a);
ptr1=&a;
ptr2=25;
printf("ptr1=%u\n",ptr1);
printf("ptr2=%u\n",ptr2);
printf("value at ptr1=%d\n",*ptr1);
printf("value at ptr2=%d\n",*ptr2);
}
Output:

Pointer to a pointer:
C programming language also provides pointer variable to store the address of another
pointer variable. This type of pointer variable is called as pointer to pointer variable.
Sometimes we also call it as double pointer.
datatype **pointer_name;
To store the address of normal variable we use single pointer variable. To store the address of
single pointer variable we use double pointer variable.
Example: Program to illustrate pointer to a pointer
#include<stdio.h>
#define max 10
void main()
{
int a=10;
int *ptr1, **ptr2;
printf("a=%d\n",a);
ptr1=&a;
printf("accessing ptr1\n");
printf("address of a = %u\n",ptr1);
printf("value of a =%d\n",*ptr1);
printf("address of pointer ptr1=%u\n",&ptr1);
ptr2 = &ptr1;
printf("Accessing ptr 2\n");
printf("address of ptr1 = %u\n",ptr2);
printf("address of a = %u\n",*ptr2);
printf("value of a = %d \n", **ptr2);
}
Output:

Pointer operations:
In c programming language, we can perform the following arithmetic operations on pointers:
• Addition of a constant
• Subtraction of a constant
• Increment
• Decrement
Example: Program to illustrate pointer operations
#include<stdio.h>
void main()
{
int i=5, *ptr;
printf("value of i = %d\n", i);
ptr=&i;
printf("address of i = %u\n", ptr);
ptr=ptr+2;
printf("After addition of 2 = %u\n", ptr);
ptr=ptr-4;
printf("After substraction of 4 = %u\n", ptr);
ptr++;
printf("After incrementation = %u\n", ptr);
ptr--;
printf("After decrementation = %u\n", ptr);
}
Output:

Array of pointers:
Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.
Syntax: int *var_name[array_size];
Declaration of an array of pointers:
int *ptr[3];
We can make separate pointer variables which can point to the different values or we can
make one integer array of pointers that can point to all the values.
Example: C program to demonstrate example of array of pointers
#include <stdio.h>
const int SIZE = 3;
void main()
{
// creating an array
int arr[] = { 1, 2, 3 };
// we can make an integer pointer array to store the address of array elements
int i, *ptr[SIZE];
for (i = 0; i < SIZE; i++) {
// assigning the address of integer.
ptr[i] = &arr[i];
}
// printing values using pointer
for (i = 0; i < SIZE; i++) {

printf("Value of arr[%d] = %d\n", i, *ptr[i]);


}
}
Output:
Value of arr[0] = 1
Value of arr[1] = 2
Value of arr[2] = 3

void pointer:
Pointer to void is the concept of defining a pointer variable that is independent of datatype.
void pointer is a pointer variable used to store the address of variable of any datatype. "void“
keyword is used to create void pointer.
Syntax: void *pointer_name ;
Example: Program to illustrate void pointer
#include<stdio.h>
void main()
{
int a=10 ;
float b=9.8;
char c='y' ;
void *ptr ;
ptr = &a ;//int
printf("a = %d, address of integer variable a = %u\n",*(int*)ptr, ptr) ;
ptr = &b ;//float
printf("b = %.2f, address of float variable b = %u\n",*(float*)ptr, ptr) ;
ptr = &c ;//char
printf("c = %c, address of character variable c = %u\n",*(char*)ptr, ptr) ;
}
Output:
a = 10, address of integer variable a = 6487572
b = 9.80, address of float variable b = 6487568
c = y, address of character variable c = 6487567

Pointers to arrays
An array name is a constant pointer to the first element of the array. Therefore, in the
declaration −
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array
balance. Thus, the following program fragment assigns p as the address of the first element
of balance −
double *p;
double balance[10];
p = balance;
It is legal to use array names as constant pointers. Therefore, *(balance + 4) is a legitimate
way of accessing the data at balance[4].
Once you store the address of the first element in 'p', you can access the array elements using
*p, *(p+1), *(p+2) and so on.
Example: Program to illustrate pointer to an array
#include<stdio.h>
void main()
{
int arr[]={5,10,15,20,25,30};
int i, *ptr;
ptr = &arr[0];
for(i=0;i<6;i++)
{
printf("arr[%d] = %d ",i,*ptr);
printf("address = %u\n",ptr);
ptr++;
}
}
Output:

Pointers to structure:
Pointer to structure holds the address of the entire structure.
It is used to create complex data structures such as linked lists, trees, graphs and so on.
The members of the structure can be accessed using a special operator called as an arrow
operator ( -> ).
Declaration
Following is the declaration for pointers to structures in C programming −
struct tagname *ptr;
For example − struct student *s −
Accessing
It is explained below how to access the pointers to structures.
Ptr-> membername;
For example − s->sno, s->sname, s->marks;
Example: Program to illustrate structure with pointers
#include<stdio.h>
#include<string.h>
struct Student
{
char name[10];
int rno;
int age;
};
void main()
{
struct Student S;
struct Student *sptr;
sptr = &S;
sptr->rno=125;
strcpy(S.name,"Mounica");
S.age=20;
printf("student 1 details using pointer:\n");
printf("Name= %s \nRoll no.= %d\nage= %d\n", sptr->name, sptr->rno, sptr->age);
}
Output:
student 1 details using pointer:
Name= Mounica
Roll no.= 125
age= 20

Self Referential Structure:


Structure that have one or more pointers which points to the same type of structure, as their
member is known as self referential structure.
Syntax:
struct struct_name
{
datatype var_name;
struct struct_name *pointer_name;
}
Example: program to create Single linked list using self referential structure
#include<stdio.h>
struct node
{
int data;
struct node *link;
};
void main()
{
struct node obj1;
//object 1 creation
obj1.data=20;
obj1.link=NULL;
printf("Object 1: %d %d\n",obj1.data,obj1.link);//20 0
//Object 2 creation
struct node obj2;
obj2.data=30;
obj2.link=NULL;
obj1.link=&obj2; //linking object 1 and object 2
printf("Object 1 (after creating object 2): %d %d\n", obj1.data, obj1.link);
printf("Object 2: %d %d\n",obj1.link->data,obj1.link->link);
}
Output:
Object 1(after creating object 2): 20 6895421
Object 2: 30 0

You might also like