0% found this document useful (0 votes)
20 views

Unit 4

Uploaded by

balaraju92466
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Unit 4

Uploaded by

balaraju92466
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Programming for Problem

Solving Using ‘C’


Unit-IV

Pointers: Definition, Pointer Compatibility, Dynamic


Memory Allocation, Pointer Arithmetic, Arrays and
Pointers, Array of pointers, Pointers and Functions, Call by
reference. Structure: Definition, Declaration, Initialization,
Nested structures, Array of structures, Self-Referential
Structures, Enumerated Data type, Structures and Functions,
Structures and Pointers; Union
Programming for Problem Solving Using ‘C’ Unit-IV

Department of Computer Science & Engineering


Programming for Problem Solving using ‘C’
(Common for Civil, ECE, MECH, EEE, CSE, CSE (DS), CSE (AI &ML)

Unit IV: Pointers and Structures 8 Hours


Pointers: Definition, Pointer Compatibility, Dynamic Memory Allocation, Pointer Arithmetic, Arrays
and Pointers, Array of pointers, Pointers and Functions, Call by reference.
Structure: Definition, Declaration, Initialization, Nested structures, Array of structures, Self-
Referential Structures, Enumerated Data type, Structures and Functions, Structures and Pointers;
Union

Pointers
Definition: The pointer in C language is a variable which stores the address of another variable.
Pointers are used to access memory and manipulate the address. This variable can be of type int, char,
array, function, or any other pointer.

Declaring Pointers (Creating Pointers):


In c programming language, declaration of pointer variable is similar to the creation of normal variable
but the name is prefixed with * symbol.
Syntax: datatype *pointerName ;

Example: int *ptr ;

Initialize a pointer:
After declaring a pointer, we initialize it like standard variables with a variable address. To get the
address of a variable, we use the ampersand (&)operator, placed before the name of a variable whose
address we need.
Syntax: pointer = &variable;
Eg: double a = 10;

Page 2 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

double *p;
p = &a;

Concept of Pointers:
int a=10;
a
10

1004
Whenever a variable is declared in a program, system allocates a location i.e an address to that
variable in the memory, to hold the assigned value.(Fig.1)
This location has its own address number
Let us assume that system has allocated memory location 80F for a variable a. (above
mentioned)

Pointer Variables:
The memory addresses are also just numbers, they can also be assigned to some other variable.
The variables which are used to hold memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some other
variable.

BENEFITS OF USING POINTERS


Pointers are more efficient in handling Arrays and Structures.
Pointers allow references to function and thereby help in passing of function as arguments to
other functions.
It reduces length of the program and its execution time as well.
It allows C language to support Dynamic Memory management.
Program:
#include<stdio.h>
void main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p

Page 3 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

printf("Address stored in a variable p is:%x \n",p); //accessing the address


printf("Value stored in a variable p is:%d \n",*p); //accessing the value
getch();
}
Output:
Address stored in a variable p is: 60ff08
Value stored in a variable p is: 10.

Address in C
If you have a variable var in your program, &var will give you its address in the memory.
We have used address numerous times while using the scanf() function.
scanf("%d", &var);
Here, the value entered by the user is stored in the address of var variable. Let's take a working
example.
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
// Notice the use of & before var
printf("address of var: %p", &var);
return 0;
}
Output
var: 5
address of var: 2686778

Note: You will probably get a different address when you run the above code.

C Pointers
Pointers (pointer variables) are special variables that are used to store addresses rather than values.
Pointer Syntax
Here is how we can declare pointers.
Page 4 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

int* p;

Here, we have declared a pointer p of int type.


You can also declare pointers in these ways.

int *p1;
int * p2;

Let's take another example of declaring pointers.


int* p1, p2;
Here, we have declared a pointer p1 and a normal variable p2.

Assigning addresses to Pointers


Let's take an example.
int* pc, c;
c = 5;
pc = &c;
Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.

Get Value of Thing Pointed by Pointers


To get the value of the thing pointed by the pointers, we use the * operator.
For example:
int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc);

// Output: 5

Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we
used *pc.
Note: In the above example, pc is a pointer, not *pc. You cannot and should not do something
like *pc = &c;
Page 5 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

By the way, * is called the dereference operator (when working with pointers). It operates on a pointer
and gives the value stored in that pointer.

Changing Value Pointed by Pointers

Let's take an example.


int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1

We have assigned the address of c to the pc pointer.


Then, we changed the value of c to 1. Since pc and the address of c is the same, *pc gives us 1.

Let's take another example.


int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1
We have assigned the address of c to the pc pointer.
Then, we changed *pc to 1 using *pc = 1;. Since pc and the address of c is the same, c will be equal
to 1.
Let's take one more example.
int* pc, c, d;
c = 5;
d = -15;
pc = &c; printf("%d", *pc); // Output: 5
pc = &d; printf("%d", *pc); // Ouptut: -15
Initially, the address of c is assigned to the pc pointer using pc = &c;. Since c is 5, *pc gives us 5.
Page 6 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Then, the address of d is assigned to the pc pointer using pc = &d;. Since d is -15, *pc gives us -15.

Example: Working of Pointers


Let's take a working example.
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output
Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11

Address of c: 2686784
Page 7 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Value of c: 2

Explanation of the program


int* pc, c;

Here, a pointer pc and a normal variable c, both of type int, is created.


Since pc and c are not initialized at initially, pointer pc points to either no address or a random
address. And, variable c has an address but contains random garbage value.

c = 22;

This assigns 22 to the variable c. That is, 22 is stored in the memory location of variable c.

pc = &c;

This assigns the address of variable c to the pointer pc.

c = 11;

This assigns 11 to variable c.

Page 8 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

*pc = 2;

This change the value at the memory location pointed by the pointer pc to 2.

POINTERS TO POINTERS:

A pointer to a pointer is a form multiple indirection, or a chain of pointers or double pointer.


Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains the actual
value as shown below.

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name.
Syntax: datatype **pointerName ; Eg:int **var;
Example Program:
#include <stdio.h>
void main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
getch();

Page 9 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000

COMPATIBILITY:
Two pointer types with the same type qualifiers are compatible if they point to objects of compatible
types. The composite type for two compatible pointer types is the similarly qualified pointer to the
composite type.
The following example shows compatible declarations for the assignment operation:
float subtotal;
float * sub_ptr;
sub_ptr = &subtotal;
printf("The subtotal is %f\n", *sub_ptr);
The next example shows incompatible declarations for the assignment operation:
double league;
int * minor;
minor = &league; /* error */

Pointers have a type associated with them, such as char, int, float, etc. Each pointer takes on the
attributes of the type to which it refers to in addition to its own attributes.
Compatibility types are:
a) Pointer Size Compatibility
b) Dereference Type Compatibility
c) Casting Pointers
d) Dereference Level Compatibility

a) Pointer Size Compatibility:


The size of all pointers is the same.
Every pointer variable holds the address of one memory location in the computer.
On the other hand, the Size of the variable that the pointer references can be different.
The pointer also takes the attributes of the type being referenced.

Page 10 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Example: Prints the size of each pointer and the size of each referenced variable
#include <stdio.h>
void main()
{
int a = 10;
int *pa = &a;
char b = 'x';
char *pb = &b;
float c = 10.01;
float *pc = &c;
printf("Pointer Example Program : Print Size of Different types Using sizeof\n");
printf("\n sizeof(a): = %d", sizeof(a));
printf("\n sizeof(*pa): = %d", sizeof(*pa));
printf("\n sizeof(b): = %d", sizeof(b));
printf("\n sizeof(*pb): = %d", sizeof(*pb));
printf("\n sizeof(c): = %d", sizeof(c));
printf("\n sizeof(*pc): = %d", sizeof(*pc));
getch();
}

Output:
Pointer Example Program : Print Size of Different types Using sizeof
sizeof(a) : = 4
sizeof(*pa) : = 4
sizeof(b) : = 1
sizeof(*pb) : = 1
sizeof(c) : = 4
sizeof(*pc) : = 4

b) Dereference Type Compatibility :


The dereference type is the type of the variable that the pointer is referencing.
It is invalid to assign a pointer of one type to a pointer of another type.
A pointer to a char is only compatible with a pointer to a char.

Page 11 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

A pointer to an int is only compatible with a pointer to an int.


Do not assign a pointer to a char to a pointer to an int.

The exception to the reference type compatibility rule is the pointer to Void.

c) Casting Pointers:
The problem of type incompatibility can be solved by using casting.
An explicit assignment between incompatible pointer types is done by using a cast operator.
For example,
pc=(char *)&a; /*pc is a character pointer and a is a integer pointer */
This converts an integer pointer to a char and assigns the value to pc.
d) Dereference Level Compatibility:
A pointer to int is not compatible with a pointer-to-pointer to int.
The pointer to int has a reference type of int, while a pointer-to-pointer to int has a reference type of
pointer to int

L VALUE AND R VALUE:


L-value: An l-value (locator value) represents an object that occupies some identifiable location in
memory. l-value may appear as either left hand or right hand side of an assignment operator(=). l-value
often represents as identifier.
The l-value is one of the following:
1. The name of the variable of any type i.e of integral, floating, pointer, structure, orunion type.
Page 12 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

2. A subscript ([ ]) expression int arr[20];


3. Aunary-indirection(*) expression. *p = 1;
4. An l-value expression in parentheses. *(p + 2) = 18;
5. A const object
6. The result of indirection through a pointer.
7. The result of member access through pointer(-> or .)
Eg: int a,b; a = 1;
b = a; // Ok, as l-value can appear on right
9 = a; // Compilation error:
R-value: r-value refers to data value that is stored at some address in memory. A r-value is an
expression that can’t have a value assigned to it, which means r-value can appear on right but not on
left hand side of an assignment operator(=).
Eg: int a = 1, b;
a + 1 = b; // Error, left expression (a + 1) is not variable

MEMORY ALLOCATION FUNCTIONS:


In C it is very convenient to allocate and de-allocate blocks of memory as and when needed. The
memory management in C can by using two types of memory spaces.
1. Static Memory
2. Dynamic Memory

1. Static memory: This is where variables, which are defined outside of functions, are located. it
specifies their scope to be local to the current module. Variables that are defined inside of a function,
which are explicitly declared static, are also stored in static memory.

2. Dynamic Memory: The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by
4 functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()

Page 13 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Function Purpose Syntax

malloc() Allocates the single block of requested malloc (number * sizeof(int));


memory and returns the pointer to the
first byte of allocated memory.
calloc() Allocates multiple blocks of requested calloc (number, sizeof(int));
memory space.Initializes the elements
to zero and returns a pointer to the
memory.
realloc() It is used to modify the size of realloc (pointer_name, number * sizeof(int));
previously allocated memory space.
free() Frees or empties the previously free (pointer_name);
allocated memory space.

1. malloc():
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldn’t able to allocate requested amount of
memory.

Syntax: ptr=(cast-type*)malloc(byte-size);

2. calloc():
The calloc() function allocates multiple block of requested memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not sufficient.

Syntax: ptr=(cast-type*)calloc(number, byte-size) ;

3. realloc():
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.

Syntax: ptr=realloc(ptr, new-size);


Page 14 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

4. free():
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.

Syntax: free(ptr);
Example:
C Program to Store Information Using Structures with Dynamic Memory Allocation
#include <stdio.h>
#include<stdlib.h>
struct course
{
int marks;
char subject[30];
};
void main()
{
struct course *ptr;
int i, noofRecords;
printf("Enter number of records: ");
scanf("%d", &noofRecords);
// Allocates the memory for noofRecords structures with pointer ptr pointing to the base
address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct course));
for(i = 0; i < noofRecords; ++i)
{
printf("Enter name of the subject and marks respectively:\n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("Displaying Information:\n"); for(i = 0; i < noofRecords ; ++i)
{
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);
}

Page 15 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

getch();
}
Output:

DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC


MEMORY ALLOCATION IN C:

Static memory allocation Dynamic memory allocation

In static memory allocation, memory is In dynamic memory allocation,


allocated while writing the C program. memory is allocated while executing
Actually, user requested memory will be the program. That means at run time.
allocated at compile time.

Memory size can’t be modified while Memory size can be modified while
execution. execution.
Example: array Example: Linked list

DIFFERENCE BETWEEN malloc() AND calloc() FUNCTIONS IN C:

malloc() calloc()

It allocates only single block of requested It allocates multiple blocks of requested


memory memory

int *ptr; int *ptr;


ptr = malloc(20 * sizeof(int)); ptr = calloc(20, sizeof(int) );
For the above, 20*4 bytes of memory only For the above, 20 blocks of memory will be
allocated in one block. created and each contains 20*4 bytes of
memory. Total = 1600 bytes
Total = 80 bytes

malloc () doesn’t initializes the allocated calloc () initializes the allocated memory to
memory. It contains garbage values zero

Page 16 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

type cast must be done since this function Same as malloc () function int *ptr;
returns void pointer ptr = (int*)calloc(20,sizeof(int));
int *ptr;
ptr = (int*)malloc(sizeof(int)*20 );

POINTER APPLICATIONS ARRAYS AND POINTERS IN C:


When an array is declared, compiler allocates sufficient amount of memory to contain all the elements
of the array. Base address i.e address of the first element of the array is also allocated by the compiler.
Suppose we declare an array arr, int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements
will be stored as follows:

Here variable arr will give the base address, which is a constant pointer pointing to the first element of
the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000.
Hence arr has two purposes
1. It is the name of the array
2. It acts as a pointer pointing towards the first element in the array.

arr is equal to &arr[0] by default


Eg: int *p;
p = arr;// or,
p = &arr[0]; //both the statements are equivalent.

Pointer to Array: We can use a pointer to point to an array, and then we can use that pointer to access
the array elements.
#include <stdio.h>
void main()
{

Page 17 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = &a[0]; // same as int*p = a;
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
getch();
}

Output:

In the above program, the pointer *p will print all the values stored in the array one by one.

POINTER ARITHMETIC:
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a numeric value.
Following arithmetic operations are possible on the pointer in C language:

4 Increment 2. Decrement 3. Addition


5 Subtraction 5. Comparison

1. Pointer increment:

Increment operator when used with a pointer variable returns next address pointed by the pointer. The
next address returned is the sum of current pointed address and size of pointer data type.

Example:
#include <stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = &a[0]; // same as int*p = a;
for (i = 0; i < 5; i++)
{
printf("Address of a[%d] = %x\n", i, p );
printf("Value of a[%d] = %d\n", i, *p );
p++;
Page 18 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

}
getch();
}
Output:

2. Pointer decrement:
Decrement operator returns the previous address pointed by the pointer. The returned address is the
difference of current pointed address and size of pointer data type.
#include <stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = &a[4]; // same as int*p = a;
for (i = 5; i > 0; i--)
{
printf("Address of a[%d] = %x\n", i, p );
printf("Value of a[%d] = %d\n", i, *p );
p--;
}
getch();
}
Output:

3. Pointer Addition:
We can add a value to the pointer variable. Adding any number to a pointer will give an address.
Syntax: new_address= current_address + (number * size_of(data type));
Example:
Page 19 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

#include<stdio.h> int main()


{
int number=50;
int *p;//pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);

p=p+3;
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output:
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312

As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312,
i.e., 4*3=12 increment,since integer value occupies 4-byte memory in 64-bit Operating system.

4. Pointer Subtraction:
Like pointer addition, we can subtract a value from the pointer variable.Subtracting any number from
a pointer will give an address.
Syntax: new_address= current_address - (number * size_of(data type));
Example:
#include<stdio.h>
int main()
{
int number=50;
int *p; //pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;

Page 20 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

}
Output:
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address
value.

5. Pointer comparison:
In C, you can compare two pointers using relational operator. You can perform six different type of
pointer comparison <, >, <=, >=, == and !=.Pointer comparison compares two pointer addresses to
which they point to, instead of comparing their values. Pointer comparisons are useful,If you want to
check if two pointer points to same location.
Example:
int main()
{
int num = 10;
int *ptr1 = &num; // ptr1 points to num
int *ptr2 = &num; // ptr2 also points to num
printf(“address of ptr1 is %u”,ptr1);
printf(“address of ptr2 is %u”,ptr2);
if(ptr1 == ptr2)
{
ptr2++;
printf(“modified address of ptr2 is %u”,ptr2);
}
return 0;
}

Output:

Page 21 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

ARRAY OF POINTERS:
Just like we can declare an array of int, float or char etc, we can also declare an array of pointers. Array
of pointers is an indexed set of variables, where the variables are pointers. An array of pointers is
useful in the same way as all arrays, that is it allows you to index a large set of variables.
Syntax: datatype *array_name[size]; Eg: int *arr[5];

Fig: Array Of Pointers


Here arr is an array of 5 integer pointers. It means that this array can hold the address of 5 integer
variables.
Example:
#include<stdio.h>
void main()
{
int *arr[3];
int a = 10, b = 20, c = 50, i; arr[0] = &a;
arr[1] = &b; arr[2] = &c;
for(i = 0; i < 3; i++)
{
printf("Address = %d\t Value = %d\n", arr[i], *arr[i]);
}
getch();
}
Output:
Address = 387130656 Value = 10
Address = 387130660 Value = 20
Address = 387130664 Value = 50

Page 22 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

PROGRAMMING APPLICATION:
Dynamic Array:
This program creates a dynamic array where the programmer can choose the number of rows and
number of elements that can be stored per a row (coloumns) dynamically at run time.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int r, c;
printf("enter number of rows you want to create \n");
scanf("%d",&r);
printf("number of elements you want to insert per row \n");
scanf("%d",&c);
int *arr = (int *)malloc(r * c * sizeof(int));
int i, j, count = 0;
for (i = 0; i < r; i++)
{
(j = 0; j < c; j++)
{
printf("%d ", *(arr + i*c + j));
}
for (j = 0; j < c; j++)
{
*(arr + i*c + j) = ++count;
}
}
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)

printf("%d ", *(arr + i*c + j));


}
}
Page 23 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

getch();
}

Output:

POINTERS AND FUNCTIONS:


C programming allows passing a pointer to a function. To do so, simply declare the
function parameter as a pointer type. Pointer as a function parameter is used to hold addresses of
arguments passed during function call. This is also known as call by reference.

Eg: [Refer program for call by reference]


Functions returning pointers:
A function can return data of types int, float, char etc. Similarly, a function can return a pointer to
data. we should not return a pointer to a local variable.
Syntax: type *function_name(type1, type2, ...);
Eg: int *func(int, int); // this function returns a pointer to int
double *func(int, int); // this function returns a pointer to double

Page 24 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Ex:
#include <stdio.h>
int* findLarger(int*, int*);
void main()
{
int numa=0; int numb=0; int *result;
printf("\n\n Pointer : Show a function returning pointer :\n");
printf(" \n");
printf(" Input the first number : ");
scanf("%d", &numa);
printf(" Input the second number : ");
scanf("%d", &numb);
result=findLarger(&numa, &numb);
printf(" The number %d is larger. \n\n",*result);
}
int* findLarger(int *n1, int *n2)
{
if(*n1 > *n2) return n1; else
return n2;
}
Output:
Pointer : Show a function returning pointer :

Page 25 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Input the first number


: 5 Input the second
number : 6 The
number 6 is larger.

Call by Reference:
In call by reference parameter passing method, the address of the actual parameters is passed to the
called function and is received by the formal parameters (pointers). Whenever we use these formal
parameters in called function, they directly access the memory locations of actual parameters. So the
changes made on the formal parameters effects the values of actual parameters.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void swap(int *,int *) ; // function declaration clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ; temp = *a ;
*a = *b ;
*b = temp ;
}
Output:

Page 26 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Structure: Definition, Declaration, Initialization, Nested structures, Array of structures, Self-


Referential Structures, Enumerated Data type, Structures and Functions, Structures and Pointers;
Union

Structures in C:
In C programming language, a structure is a collection of elements of the different data type. The
structure is used to create user-defined data type in the C programming language. As the structure used
to create a user-defined data type, the structure is also said to be “user-defined data type in C”.
In other words, a structure is a collection of non-homogeneous elements. Using structure we can define
new data types called user-defined data types that holds multiple values of the different data type. The
formal definition of structure is as follows...
Structure is a collection of different type of elements under a single name that acts as
user defined data type in C.
Generally, structures are used to define a record in the c programming language. Structures allow us to
combine elements of a different data type into a group. The elements that are defined in a structure are
called members of structure.
How to create structure?
To create structure in c, we use the keyword called "struct". We use the following syntax to create
structures in c programming language.

struct <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};
Following is the example of creating a structure called Student which is used to hold student record.
Creating structure in C
struct Student
{
char stud_name[30];
int roll_number;
float percentage;
};
Importent Points to be Remembered:
Every structure must terminated with semicolon symbol (;).
"struct" is a keyword, it must be used in lowercase letters only.
Page 27 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Creating and Using structure variables


In a c programming language, there are two ways to create structure variables. We can create structure
variable while defining the structure and we can also create after terminating structure using struct
keyword.
To access members of a structure using structure variable, we use dot (.) operator. Consider the
following example code...
Creating and Using structure variables in C
struct Student
{
char stud_name[30];
int roll_number;
float percentage;
} stud_1 ; // while defining structure
void main()
{
struct Student stud_2; // using struct keyword
printf("Enter details of stud_1 : \n");
printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);
printf("***** Student 1 Details *****\n);
printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Percentage of the Student : %f\n", stud_1.percentage);
}
In the above example program, the stucture variable "stud_1 is created while defining the structure and
the variable "stud_2 is careted using struct keyword. Whenever we access the members of a structure
we use the dot (.) operator.
Memory allocation of Structure
When the structures are used in the c programming language, the memory does not allocate on
defining a structure. The memory is allocated when we create the variable of a particular structure. As
Page 28 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

long as the variable of a structure is created no memory is allocated. The size of memory allocated is
equal to the sum of memory required by individual members of that structure. In the above example
program, the variables stud_1 and stud_2 are allocated with 36 bytes of memory each.

Important Points to be Remembered


All the members of a structure can be used simultaneously.
Until variable of a structure is created no memory is allocated.
The memory required by a structure variable is sum of the memory required by individual
members of that structure.
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that we
wish to access. You would use the keyword struct to define variables of structure type. The following
example shows how to use a structure in a program −
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
Page 29 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

struct Books Book2; /* Declare Book2 of type Book */


/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}

When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Page 30 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Nested structures:
C provides us the feature of nesting one structure within another structure by using which, complex
data types are created. For example, we may need to store the address of an entity employee in a
structure. The attribute address may also have the subparts as street number, city, state, and pin code.
Hence, to store the address of the employee, we need to store the address of the employee into a
separate structure and nest the structure address into the structure employee.
Consider the following program.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information. .. \n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.a
dd.phone);
}

Output
Enter employee information?
Arun
Delhi
110001
Page 31 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
The structure can be nested in the following ways.
1. By separate structure
2. By Embedded structure

1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main structure as
a member.
Consider the following example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in
Employee structure. In this way, we can use Date structure in many structures.

2) Embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence, it requires less
line of codes but it cannot be used in multiple data structures. Consider the following example.
struct Employee
Page 32 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;

Accessing Nested Structure


We can access the member of the nested structure by Outer_Structure.Nested_Structure.member as
given below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy

C Nested Structure example


Let's see a simple example of the nested structure in C language.
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
Page 33 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}

Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014

C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by using the structure as
given below.

#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
Page 34 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

void main()
{
struct student s1,s2,s3;
int dummy;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
printf("Printing the details. .. \n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
Output
Enter the name, id, and marks of student 1 James 90 90
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However, the complexity of
the program will be increased if there are 20 students. In that case, we will have to declare 20 different
structure variables and store them one by one. This will always be tough since we will have to declare
a variable every time we add a student. Remembering the name of all the variables is also a very tricky
task. However, c enables us to declare an array of structures by using which, we can avoid declaring
the different structure variables; instead we can make a collection containing all the structures that
store the information of different entities.

Page 35 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Array of Structures in C
An array of structres in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array of structures is also known as the
collection of structures.

Let's see an example of an array of structures that stores information of 5 students and prints it.
#include<stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);

Page 36 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

Self Referential Structures


Self Referential structures are those structures that have one or more pointers which point to the same
type of structure, as their member.

Page 37 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

In other words, structures pointing to the same type of structures are self-referential in nature.
Example:

struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}

In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a
self-referential structure with ‘link’ as the referencing pointer.

An important point to consider is that the pointer should be initialized properly before accessing, as by
default it contains garbage value.

Types of Self Referential Structures


1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links

1. Self Referential Structure with Single Link: These structures can have only one self-pointer
as their member. The following example will show us how to connect the objects of a self-
referential structure with the single link and access the corresponding data members. The
connection formed is shown in the following figure.

Page 38 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

#include <stdio.h>
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}

Output:
30
40

Page 39 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

2. Self Referential Structure with Multiple Links: Self referential structures with multiple links can
have more than one self-pointers. Many complicated data structures can be easily constructed using
these structures. Such structures can easily connect to more than one nodes at a time. The following
example shows one such structure with more than one links.
The connections made in the above example can be understood using the following figure.

#include <stdio.h>
struct node
{
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;
struct node ob2; // Node2
// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;

Page 40 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

struct node ob3; // Node3


// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;
// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;
// Accessing data of ob1, ob2 and ob3 by ob1
printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob2
printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);
// Accessing data of ob1, ob2 and ob3 by ob3
printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}

Output:
10 20 30
10 20 30
10 20 30
In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self referential
structure ‘node’. And they are connected using their links in such a way that any of them can easily

Page 41 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

access each other’s data. This is the beauty of the self referential structures. The connections can be
manipulated according to the requirements of the programmer.

Applications:

Self referential structures are very useful in creation of other complex data structures like:
1. Linked Lists 2. Stacks 3. Queues
4. Trees 5. Graphs etc

Enumerated Data type:


The enum in C is also known as the enumerated type. It is a user-defined data type that consists of
integer values, and it provides meaningful names to these values. The use of enum in C makes the
program easy to understand and maintain. The enum is defined by using the enum keyword.
The following is the way to define the enum in C:
enum flag{integer_const1, integer_const2,. integter_constN};
In the above declaration, we define the enum named as flag containing 'N' integer constants. The
default value of integer_const1 is 0, integer_const2 is 1, and so on. We can also change the default
value of the integer constants at the time of the declaration.
For example:
enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3. If we want to change
these default values, then we can do as given below:
enum fruits
{
mango=2,
apple=1,
strawberry=5,
papaya=7,
};
Enumerated type declaration
As we know that in C language, we need to declare the variable of a pre-defined type such as int, float,
char, etc. Similarly, we can declare the variable of a user-defined data type, such as enum. Let's see
how we can declare the variable of an enum type.
Suppose we create the enum of type status as shown below:
enum status{false,true};

Page 42 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Now, we create the variable of status type:


enum status s; // creating a variable of the status type.
In the above statement, we have declared the 's' variable of type status.
To create a variable, the above two statements can be written as:
enum status{false,true} s;
In this case, the default value of false will be equal to 0, and the value of true will be equal to 1.
Let's create a simple program of enum.
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}
In the above code, we create an enum type named as weekdays, and it contains the name of all the
seven days. We have assigned 1 value to the Sunday, and all other names will be given a value as the
previous value plus one.
Output

Let's demonstrate another example to understand the enum more clearly.


#include <stdio.h>
enum months{jan=1, feb, march, april, may, june, july, august, september, october, november, decem
ber};
int main()
{
// printing the values of months

Page 43 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

for(int i=jan;i<=december;i++)
{
printf("%d, ",i);
}
return 0;
}
In the above code, we have created a type of enum named as months which consists of all the names of
months. We have assigned a '1' value, and all the other months will be given a value as the previous
one plus one. Inside the main() method, we have defined a for loop in which we initialize the 'i'
variable by jan, and this loop will iterate till December.
Output

Why do we use enum?


The enum is used when we want our variable to have only a set of values. For example, we create a
direction variable. As we know that four directions exist (North, South, East, West), so this direction
variable will have four possible values. But the variable can hold only one value at a time. If we try to
provide some different value to this variable, then it will throw the compilation error.
The enum is also used in a switch case statement in which we pass the enum variable in a switch
parenthesis. It ensures that the value of the case block should be defined in an enum.
Let's see how we can use an enum in a switch case statement.
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum days d;
d=monday;
switch(d)
{
case sunday:
printf("Today is sunday");

Page 44 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}
return 0;
}
Output

Some important points related to enum


The enum names available in an enum type can have the same value. Let's look at the example.
#include <stdio.h>
int main(void)
{

Page 45 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

enum fruits{mango = 1, strawberry=0, apple=1};


printf("The value of mango is %d", mango);
printf("\nThe value of apple is %d", apple);
return 0;
}
Output

If we do not provide any value to the enum names, then the compiler will automatically assign
the default values to the enum names starting from 0.
We can also provide the values to the enum name in any order, and the unassigned names will
get the default value as the previous one plus one.
The values assigned to the enum names must be integral constant, i.e., it should not be of other
types such string, float, etc.
All the enum names must be unique in their scope, i.e., if we define two enum having same
scope, then these two enums should have different enum names otherwise compiler will throw
an error.
Let's understand this scenario through an example.
#include <stdio.h>
enum status{success, fail};
enum boolen{fail,pass};
int main(void)
{
printf("The value of success is %d", success);
return 0;
}
Output

In enumeration, we can define an enumerated data type without the name also.
#include <stdio.h>
enum {success, fail} status;
Page 46 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

int main(void)
{
status=success;
printf("The value of status is %d", status);
return 0;
}
Output

Enum vs. Macro in C


Macro can also be used to define the name constants, but in case of an enum, all the name constants
can be grouped together in a single statement.
For example,
# define pass 0;
# define success 1;

The above two statements can be written in a single statement by using the enum type.
enum status{pass, success};
The enum type follows the scope rules while macro does not follow the scope rules.
In Enum, if we do not assign the values to the enum names, then the compiler will
automatically assign the default value to the enum names. But, in the case of macro, the values
need to be explicitly assigned.
The type of enum in C is an integer, but the type of macro can be of any type.

typedef in C
The typedef is a keyword used in C programming to provide some meaningful names to the already
existing variable in the C program. It behaves similarly as we define the alias for the commands. In
short, we can say that this keyword is used to redefine the name of an already existing variable.
Syntax of typedef
typedef <existing_name> <alias_name>

In the above syntax, 'existing_name' is the name of an already existing variable while 'alias name' is
another name given to the existing variable.
For example, suppose we want to create a variable of type unsigned int, then it becomes a tedious task
if we want to declare multiple variables of this type. To overcome the problem, we use a
typedef keyword.

Page 47 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

typedef unsigned int unit;


In the above statements, we have declared the unit variable of type unsigned int by using a
typedef keyword.
Now, we can create the variables of type unsigned int by writing the following statement:
unit a, b;
instead of writing:
unsigned int a, b;
Till now, we have observed that the typedef keyword provides a nice shortcut by providing an
alternative name for an already existing variable. This keyword is useful when we are dealing with the
long data type especially, structure declarations.

Let's understand through a simple example.


#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
Output
Value of i is :10
Value of j is :20
Using typedef with structures
Consider the below structure declaration:
struct student
{
char name[20];
int age;
};
struct student s1;
Page 48 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

In the above structure declaration, we have created the variable of student type by writing the
following statement:
struct student s1;
The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To avoid
such a big statement, we use the typedef keyword to create the variable of type student.
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
In the above statement, we have declared the variable stud of type struct student. Now, we can use
the stud variable in a program to create the variables of type struct student.

The above typedef can be written as:


typedef struct student
{
char name[20];
int age;
} stud;
stud s1,s2;

From the above declarations, we conclude that typedef keyword reduces the length of the code and
complexity of data types. It also helps in understanding the program.

Let's see another example where we typedef the structure declaration.


#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
Page 49 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}

Output

Enter the details of student s1:


Enter the name of the student: Peter
Enter the age of student: 28
Name of the student is : Peter
Age of the student is : 28
Using typedef with pointers
We can also provide another name or alias name to the pointer variables with the help of the typedef.
For example, we normally declare a pointer, as shown below:
int* ptr;
We can rename the above pointer variable as given below:
typedef int* ptr;
In the above statement, we have declared the variable of type int*. Now, we can create the variable of
type int* by simply using the 'ptr' variable as shown in the below statement:
ptr p1, p2 ;
In the above statement, p1 and p2 are the variables of type 'ptr'.

Structures and Functions


You can pass a structure as a function argument in the same way as you pass any other variable or
pointer.

Page 50 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
Page 51 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Structures and Pointers


You can define pointers to structures in the same way as you define pointer to any other variable −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To find
the address of a structure variable, place the '&'; operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the → operator as
follows −
struct_pointer->title;
Let us re-write the above example using structure pointer.
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];

Page 52 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Page 53 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Book author : Nuha Ali


Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Union:
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your program.
The format of the union statement is as follows −
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the union's definition, before the final
semicolon, you can specify one or more union variables but it is optional. Here is the way you would
define a union type named Data having three members i, f, and str −
union Data
{
int i;
float f;
char str[20];
} data;
Page 54 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It
means a single variable, i.e., same memory location, can be used to store multiple types of data. You
can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in the above example, Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a character string. The following example displays the total
memory size occupied by the above union −
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to
access. You would use the keyword union to define variables of union type. The following example
shows how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
Page 55 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that the values of i and f members of union got corrupted because the final value
assigned to the variable has occupied the memory location and this is the reason that the value
of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the
main purpose of having unions −
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
Page 56 of 57
Programming for Problem Solving Using ‘C’ Unit-IV

printf( "data.i : %d\n", data.i);


data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.

Differences: Structures & Union

X
R a md a s K a p ila
A s s is t a n t P ro f e s s o r , N S R IT

Page 57 of 57

You might also like