0% found this document useful (0 votes)
5 views54 pages

Module 5 - Strings - Pointers - Structure - PDF

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views54 pages

Module 5 - Strings - Pointers - Structure - PDF

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

Structures

1
What is a Structure?
„ Used for handling a group of logically
related data items
Examples:
„ Student name, roll number, and marks
„ Real part and complex part of a complex number

„ Helps in organizing complex data in a more


meaningful way
„ The individual structure elements are
called members
2
Defining a Structure
struct tag {
member 1;
member 2;
:
member m;
};

struct is the required C keyword


tag is the name of the structure
member 1, member 2, … are individual member
declarations

3
Contd.
„ The individual members can be ordinary
variables, pointers, arrays, or other structures
(any data type)
The member names within a particular
structure must be distinct from one another
A member name can be the same as the
name of a variable defined outside of the
structure
„ Once a structure has been defined, the
individual structure-type variables can be
declared as:
struct tag var_1, var_2, …, var_n;

4
Example
„ A structure definition
struct student {
char name[30];
int roll_number;
int total_marks;
char dob[10];
};

„ Defining structure variables:


struct student a1, a2, a3;

A new data-type
5
A Compact Form
„ It is possible to combine the declaration of the
structure with that of the structure variables:

struct tag {
member 1;
member 2;
:
member m;
} var_1, var_2,…, var_n;

„ Declares three variables of type struct tag


„ In this form, tag is optional 6
Accessing a Structure
„ The members of a structure are processed
individually, as separate entities
Each member is a separate variable
„ A structure member can be accessed by writing
variable.member
where variable refers to the name of a structure-type
variable, and member refers to the name of a
member within the structure
„ Examples:
a1.name, a2.name, a1.roll_number, a3.dob

7
Example: Complex number addition
void main()
{
struct complex
{
float real;
float cmplex;
} a, b, c;

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


scanf (“%f %f”, &b.real, &b.cmplex);

c.real = a.real + b.real;


c.cmplex = a.cmplex + b.cmplex;
printf (“\n %f + %f j”, c.real, c.cmplex);
}
8
Operations on Structure
Variables
„ Unlike arrays, a structure variable can be directly
assigned to another structure variable of the
same type
a1 = a2;
„ All the individual members get assigned

„ Two structure variables can not be compared


for equality or inequality
if (a1 == a2)…… this cannot be done

9
Arrays of Structures
„ Once a structure has been defined, we can
declare an array of structures
struct student class[50];

type name

The individual members can be accessed as:


class[i].name
class[5].roll_number
10
Arrays within Structures
„ A structure member can be an array
struct student
{
char name[30];
int roll_number;
int marks[5];
char dob[10];
} a1, a2, a3;
„ The array element within the structure can
be accessed as:
a1.marks[2], a1.dob[3],…
11
Structure Initialization
„ Structure variables may be initialized following
similar rules of an array. The values are
provided within the second braces separated
by commas
„ An example:
struct complex a={1.0,2.0}, b={-3.0,4.0};

a.real=1.0; a.imag=2.0;
b.real=-3.0; b.imag=4.0;
12
Parameter Passing in a
Function
„ Structure variables can be passed as parameters like
any other variables. Only the values will be copied
during function invocation

void swap (struct complex a, struct complex b)


{
struct complex tmp;

tmp=a;
a=b;
b=tmp;
} 13
Returning structures
„ It is also possible to return structure values from a
function. The return data type of the function should
be as same as the data type of the structure itself
struct complex add(struct complex a, struct complex b)
{
struct complex tmp;

tmp.real = a.real + b.real;


tmp.imag = a.imag + b.imag;
return(tmp);
}

Direct arithmetic operations are not possible with structure variables


14
Defining data type: using typedef
„ One may define a structure data-type with a single
name
typedef struct newtype {
member-variable1;
member-variable2;
.
member-variableN;
} mytype;
„ mytype is the name of the new data-type
Also called an alias for struct newtype
Writing the tag name newtype is optional, can be
skipped
Naming follows rules of variable naming
15
typedef : An example
typedef struct {
float real;
float imag;
} _COMPLEX;

„ Defined a new data type named _COMPLEX. Now


can declare and use variables of this type

_COMPLEX a, b, c;
16
„ Note: typedef is not restricted to just structures,
can define new types from any existing type
„ Example:
typedef int INTEGER
Defines a new type named INTEGER from the
known type int
Can now define variables of type INTEGER which
will have all properties of the int type

INTEGER a, b, c;

17
The earlier program using typedef
typedef struct{
float real;
float imag;
} _COMPLEX;

void swap (_COMPLEX a, _COMPLEX b)


{
_COMPLEX tmp;

tmp = a;
a = b;
b = tmp;
}
18
Contd.
void print (_COMPLEX a)
{
printf("(%f, %f) \n",a.real,a.imag);
}

void main()
{
_COMPLEX x={4.0,5.0}, y={10.0,15.0};

print(x); print(y);
swap(x,y);
print(x); print(y);
} swap.c 19
„ Output:
(4.000000, 5.000000)
(10.000000, 15.000000)
(4.000000, 5.000000)
(10.000000, 15.000000)

„ x and y are not swapped! But that has got


nothing to do with structures specially. We
will see its reason shortly

20
Structures and Functions
„ A structure can be passed as argument to
a function
„ A function can also return a structure

21
Example: complex number addition
void main()
{
_COMPLEX a, b, c;
scanf(“%f %f”, &a.real, &a.imag);
scanf(“%f %f”, &b.real, &b.imag);
c = add (a, b) ;
printf(“\n %f %f”, c,real, c.imag);
}
_COMPLEX add(_COMPLEX x, _COMPLEX
y)
{
_COMPLEX t;

t.real = x.real + y.real;


t.imag = x.imag + y.imag ;
return (t) ;
22
}
Exercise Problems
1. Extend the complex number program to include
functions for addition, subtraction, multiplication, and
division
2. Define a structure for representing a point in two-
dimensional Cartesian co-ordinate system
• Write a function to compute the distance between
two given points
• Write a function to compute the middle point of the
line segment joining two given points
• Write a function to compute the area of a triangle,
given the co-ordinates of its three vertices
23
MODULE-5
POINTERS

POINTERS
Pointers are variables that hold address of another variable of same data type. Pointers are
one of the most distinct and exciting features of C language. It provides power and flexibility to
the language. Although pointer may appear little confusing and complicated in the beginning, but
trust me its a powerful tool and handy to use once its mastered.
Benefit of using pointers
 Pointers are more efficient in handling Array and Structure.
 Pointer allows references to function and thereby helps in passing of function as
arguments to other function.
 It reduces length and the program execution time.
 It allows C to support dynamic memory management.
Concept of Pointer
Whenever a variable is declared, system will allocate a location to that variable in the
memory, to hold value. This location will have its own address number. Let us assume that
system has allocated memory location 80F for a variable a. int a = 10 ;

The value 10 can be accessed by either using the variable name a or the address
80F.Since the memory addresses are simply numbers they can be assigned to some other
variable. The variable that holds memory address are called pointer variables. A pointer
variable is therefore nothing but a variable that contains an address, which is a location of
another variable. Value of pointer variable will be stored in another memory location.

Supriya C, Dept of ISE,AIT, Bangalore Page 1


Declaring a pointer variable
General syntax of pointer declaration is, data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is pointing. void
type pointer works with all data types, but isn't used oftenly.

Initialization of Pointer variable


Pointer Initialization is the process of assigning address of a variable to pointer
variable. Pointer variable contains address of variable of same data type. In C language address
operator & is used to determine the address of a variable. The & (immediately preceding a
variable name) returns the address of the variable associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
Pointer variable always points to same type of data.
float a;
int *ptr;
ptr = &a;
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of
variable, pointer is dereferenced, using the indirection operator * .
int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.

Supriya C, Dept of ISE,AIT, Bangalore Page 2


printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.

Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to
contain all the elements of the array. Base address which gives location of the first element 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 byte,
the five element will be stored as follows in figure 6

Array Representation

Here variable arr will give the base address, which is a constant pointer pointing to
the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use
that pointer to access the array. Lets have an example,

Supriya C, Dept of ISE,AIT, Bangalore Page 3


int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in the array one by one.
We can also use the Base address (a in above case) to act as pointer and print all the
values.

Pointers to multidimensional array


A multidimensional array is of form, a[i][j] . Lets see how we can make a pointer point to
such an array. As we know now, name of the array gives its base address. In a[i][j] , a will give
the base address of this array, even a+0+0 will also give the base address, that is the address of
a[0][0] element. Here is the generalized form for using pointer with multidimensional arrays.
*(*(ptr + i) + j)is same as a[i][j]

Supriya C, Dept of ISE,AIT, Bangalore Page 4


Pointer and Character strings
Pointer can also be used to create strings. Pointer variables of char type are treated as
string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now points
to the first character of the string "Hello". Another important thing to
note that string created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //this is Legal
The content of the string can be printed using printf() and puts() .
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to
use indirection operator *.

Array of Pointers
Array of pointers can also be declared. Pointers are very helpful in handling character
array with rows of varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam", "chris",
"Deniel"
};

Supriya C, Dept of ISE,AIT, Bangalore Page 5


Array of pointers

The above figure shows the array of pointers used to store the character arrays. The
pointers hold the address of each of the string. Each pointer will point to the first character of
their respective strings.
Pointer to a Pointer
Just as we have pointers to int, float or char, we can also have pointers to pointers. This is
because, a pointer is also a variable. Hence, we can always have another variable (pointer) which
can contain the address of the pointer variable.

EX:
int a = 10; // integer variable
int *p; // pointer to an integer
int **q; // pointer to a pointer to an integer
p = &a;
q = &p;

This is pictorially as shown below.

The above shows a 2-level indirection, however, there is no limit as to how many levels of
indirection we can use.
Here,

Supriya C, Dept of ISE,AIT, Bangalore Page 6


q p a

3000 2000 10

4000 3000 2000

 p is the address of ‘a’ (2000)


 *p is the contents or value at address 2000 i.e. 10
 q is the address of p (3000)
 *q is the contents or value at address 3000 (2000)
 **q is the contents or value at address 2000 (10)
 a = *p = **q

Comparison of Pass by Value and Pass by Reference


Sl
Pass by Value Pass by Reference
no.
Values of variables are passed in the Addresses of the variables are passed in the
1
function call. function call.
The type of actual and formal The type of actual and formal parameters must be
2 parameters must be same. same and the formal parameters must be declared
as pointers.
Formal parameters contain the values Formal parameters contain the addresses of actual
3
of actual parameters. parameters.
The actual parameters are not The actual parameters are changed when the
4 changed when the formal parameters formal parameters are changed.
are changed.
Less information transfer. Only one More information transfer as changes made to
5
value can be returned. formal parameters change actual parameters.

Supriya C, Dept of ISE,AIT, Bangalore Page 7


*Program to swap two numbers using functions
#include<stdio.h>
void swap(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}
void main()
{
int a,b;
printf("Enter two nos :");
scanf("%d%d",&a,&b);
printf("Before swapping A:%d and B:%d\n",a,b);
swap(&a,&b);
printf("After swapping A:%d and B:%d",a,b);
}
Memory Allocation
Static Memory Allocation
It is a process where in the memory space is allocated during the compilation time. Here the
allocated memory space cannot be expanded or reduced to accommodate more or less data, i.e.
the size of the allocated memory space is fixed and it cannot be altered during execution.

EX: Consider the declaration int a[10];

During compilation, the compiler will allocate 10 memory locations for the variable ‘a’ and once
defined cannot be changed. During execution we cannot have more than 10 data items, and if we
use 3 locations, another 7 locations are wasted.

Supriya C, Dept of ISE,AIT, Bangalore Page 8


Disadvantages:
In this type of memory allocation, the data structures require a fixed amount of storage. Since the
amount of storage is fixed,
 If the data structure in use, uses only a small amount of memory, rest of the memory is
wasted.
 If the data structure in use, tries to use more memory than actually allocated for it results
in an overflow.
Because of these limitations, this type of memory allocation can be used in applications where
the data size is fixed and known before processing.
Dynamic Memory Allocation
It is the process of allocating memory space during run time. This type of memory allocation can
be used in applications where the storage requirement is unpredictable.
The following are the functions using which additional memory space can be allocated or
unwanted space can be deleted, thereby optimizing the use of storage space.

1. malloc
Description: This function allocates and reserves a block of memory, specified in bytes and
returns a pointer to the first byte of the allocated space.
Syntax:
ptr = (datatype *) malloc (size);
Where - ptr is a pointer of type datatype
- datatype can be any of the basic data type or user defined data type.
- size is the number of bytes required.
Example: ptr = ( int * ) malloc ( sizeof ( int ) );
On successful execution of this statement, a memory space equivalent to size of int is
reserved and the address of the first byte of the memory allocated is assigned to the pointer
ptr of type int.
Return Value – On success, it returns a pointer of type void to the newly allocated block of
memory. On failure i.e. if the specified size of memory is not available, it returns NULL.

Supriya C, Dept of ISE,AIT, Bangalore Page 9


2. calloc
Description – This function allocates multiple blocks of same size, initializes all locations to
zero and returns a pointer to the first byte of allocated space.
Syntax:
ptr = (datatype *) calloc (n, size);
Where - ptr is a pointer of type datatype
- datatype can be any of the basic data type or user defined data type.
- size is the number of bytes required.
- n is the number of blocks to be allocated of size bytes.
Example: ptr = ( int * ) calloc (200, sizeof ( int ) );
On successful execution of this statement, a memory space equivalent to size of 200 int
(array of 200 integers) is reserved and the address of the first byte of the memory allocated is
assigned to the pointer ptr of type int.
Return Value – On success, it returns a pointer of type void to the newly allocated block of
memory. On failure i.e. if the specified size of memory is not available, it returns NULL.

3. realloc
Description – This function is used to alter the size of the previously allocated space which
is allocated either by using malloc or calloc function.
Syntax:
ptr = (datatype *) realloc (ptr, size);
Where - ptr is the starting address of allocated memory obtained previously by calling
malloc, calloc, or realloc functions.
- size is the number of bytes required for reallocation. The size specified may be
larger or smaller than the previously allocated memory.
Example:
If the original allocation is done by the statement
ptr = malloc(size);
Then reallocation of space may be done by the statement
ptr = realloc(ptr, newsize)

Supriya C, Dept of ISE,AIT, Bangalore Page 10


On successful execution of this statement, realloc allocates a new memory space of size
newsize to the pointer variable ptr and returns a pointer to the first byte of the new memory
block.
Return Value – On success, it returns a pointer to the newly allocated block of memory. On
failure i.e. if the specified size of memory is not available, it returns NULL.
Note:
 The storage space allocated dynamically has no name and therefore its contents can
be accessed only through a pointer.

 It is the responsibility of a programmer to de-allocate memory whenever it is not


required by the application.

 In case of realloc( ), the contents of the old block will be copied into the newly
allocated space and so, this function guarantees that the earlier contents are not lost.

4. free
Description – This function de-allocates (frees) the allocated block of memory which is
allocated by using the functions malloc( ), calloc( ) or realloc( ).
Syntax:
free(ptr);
Where ptr is a pointer to a memory block which has already been created by invoking one of
the 3 functions malloc( ), calloc( ) or realloc( ).
Return Value – None.

Problems with Dynamic Memory Allocation

1. Memory Leakage
This is a problem where in a part of the memory is reserved but is not accessible to any of the
applications.
Example: Consider the following program segment.
main ( )
{
int *a;
a = (int *)malloc(sizeof (int) );

Supriya C, Dept of ISE,AIT, Bangalore Page 11


*a =10;
a = (int *)malloc(sizeof (int) );
*a =20;
}
Here, memory for the variable ‘a’ is allocated twice. However, ‘a’ contains the address of
most recently allocated memory, thereby making the earlier allocated memory inaccessible
i.e. the memory location where the value 10 is stored is inaccessible to any of the application
and is not possible to free so that it can be reused.

2. Dangling Pointer

Any pointer pointing to a destroyed object or which does not contain a valid address is called
a dangling pointer.
Example: Consider the following program segment
main ( )
{
int *a;
a =(int *)malloc(sizeof(int));
*a=20;
…….
…….
free(a);
}
Here, if we de-allocate the memory for the variable ‘a’ using free(a), the memory location
pointing to by it is returned to the free pool. Now the pointer variable ‘a’ can be used, but the
contents pointed by that cannot be used, because the pointer variable ‘a’ does not contain a
valid address now and is called a dangling pointer.

Comparison of Malloc and Calloc

Supriya C, Dept of ISE,AIT, Bangalore Page 12


Sl
Malloc ( ) Calloc ( )
no.
Syntax: Syntax:
ptr = (datatype*) malloc ( size ) ptr = (datatype*) calloc (n, size )
1 (Takes only one argument which is the (Takes 2 arguments, first is number of blocks
size of the block) to be allocated and second is the size of each
block)
Allocates a block of memory of specified Allocates multiple blocks of memory, each
2
size. block with same size.
Allocated space will not be initialized. Each byte of the allocated space is initialized
3
to zero.
Since no initialization takes place, time calloc( ) is computationally more expensive
4 efficiency is higher than calloc( ) because of zero filling but, occasionally, more
convenient than malloc( )
This function can allocate the required This function can allocate the required
size of memory even if the memory is not number of blocks contiguously. If the required
5
available contiguously but available at memory cannot be allocated contiguously, it
different locations. returns NULL.

Comparison of Static and Dynamic Memory Allocation

Sl
Static Memory Allocation Dynamic Memory Allocation
no.
Memory is allocated during compilation Memory is allocated during run time.
1
time.
The size of the allocated memory space is The size of the allocated memory space is
2 fixed and it cannot be altered during not fixed and it can be altered (increased /
execution. decreased) during execution.
This type of memory allocation can be used This type of memory allocation can be used
3
in applications where the data size is fixed in applications where the storage

Supriya C, Dept of ISE,AIT, Bangalore Page 13


and known before processing. requirement is unpredictable.
Execution is faster because memory is Execution is slower because memory is has
4 already allocated and only data to be allocated and only then data
manipulation is done. manipulation is done.
Part of memory allocated is stack memory Part of memory allocated is heap memory
5
or global/static memory.
6 Ex: arrays Ex: Dynamic arrays, linked lists

Pointers can be Dangerous


 Explain about how uninitialized pointers cause problems.
 Explain about dangling pointer
1) Program to print the elements of an array along with their address using pointers.
#include<stdio.h>
void main()
{
int a[20],n,*p,i;
p=a;
printf("How many elements you wish to enter? ");
scanf("%d",&n);
printf("Enter the elements :");
for(i=0;i<n;i++)
scanf("%d",(p+i));
printf("The elements are :\n");
for(i=0;i<n;i++)
printf("%d\t%u\n",*(p+i),p+i);
}
2) Program to find the sum of all elements in an array using pointers.
#include<stdio.h>
void main()
{
int a[20],*p,i,n,sum=0;

Supriya C, Dept of ISE,AIT, Bangalore Page 14


printf("How many array elements you wish to enter? ");
scanf("%d",&n);
printf("Enter the elements :");
for(i=0;i<n;i++)
{
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("Sum : %d",sum);
}

3) Program to read and print an array of MXN matrix using pointers.


#include<stdio.h>
void main()
{
int a[20][20],m,n,i,j,*p;
p=a;
printf("Enter the order of the matrix :");
scanf("%d%d",&m,&n);
printf("Enter the elements :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",*(p+i)+j);
}
printf("The elements are :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",*(*(p+i)+j));
printf("\n");

Supriya C, Dept of ISE,AIT, Bangalore Page 15


}
}
4) Write a C program to read array elements and display array elements using
Dynamic memory allocation. (using malloc)
void main()
{
int *p,n,i;
printf(“Enter the number of integers to be entered”);
scanf(“%d”,&n);
p=(int *)malloc(n*sizeof(int)); /* This is same as “(int *)calloc(n,sizeof(int))”*/
/* If we write “(int *)malloc(sizeof(int))” then only 2 byte of memory will be allocated
dynamically*/
if(p==NULL)
{
printf(“Memory is not available”); exit(1);
}
for(i=0;i<n;i++)
{
printf(“Enter an integer”);
scanf(“%d”,p+i);
}
for(i=0;i<n;i++)
printf(”%d\t”,*(p+i));
}
5) Write a C program to read array elements and display array elements using
Dynamic memory allocation. (using calloc)
#include<stdio.h>
void main()
{
int *p,n,i;
printf("Enter the no of elements :");

Supriya C, Dept of ISE,AIT, Bangalore Page 16


scanf("%d",&n);
p=(int*)calloc(n,sizeof(int));
printf("Enter the elements :\n");
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("The elements are :\n");
for(i=0;i<n;i++)
printf("%d\t",*(p+i));
}

6) Program to find the sum of positive and negative numbers out of ‘n’ elements using
dynamic arrays.
#include<stdio.h>
main()
{
int i,n,*a,psum,nsum;
printf("enter the number of elements \n");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
printf("enter the elements\n");
for(i-0;i<n;i++)
{
scanf("%d",a+i);
}
psum=0;
nsum=0;
for(i=0;i<n;i++)
{
if(*(a+i)>0)
{
psum=psum+*(a+i);

Supriya C, Dept of ISE,AIT, Bangalore Page 17


}
else
{
nsum=nsum+*(a+i);
}
}
printf("positive sum=%d\n negative sum=%d\n",psum,nsum);
free(a);
}

7) Program to find maximum of ‘n’ elements using dynamic arrays


#include<stdio.h>
main()
{
int n,i,*a,max;
printf("enter the number of elements \n");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
printf("enter the elements\n");
for(i=0;i<n;i++)
{
scanf("%d",a+i);
}
max=*(a+0);
for(i=1;i<n;i++)
{
if(*(a+i)>max)
{
max=*(a+i);
}
}

Supriya C, Dept of ISE,AIT, Bangalore Page 18


printf("maximum element=%d\n",max);
free(a);
}

Generalized macro to allocate memory using malloc function

If we frequently allocate the memory space,then it is better to use functions as below where n is
number of items.
Functions to allocate memory for integers, floats, chars and double

1) Allocating memory for integers


int* MALLOC_INT(int n)
{
int *x;
x=(int*)malloc(n*sizeof(int));
if(x==NULL)
{
printf(“Insufficient memory\n”);
exit(0);
}
return x;
}
2) Allocating memory for floats

int* MALLOC_FLOAT(int n)
{
float *x;
x=(float*)malloc(n*sizeof(float));
if(x==NULL)
{
printf(“Insufficient memory\n”);

Supriya C, Dept of ISE,AIT, Bangalore Page 19


exit(0);
}
return x;
}
3) Allocating memory for characters

int* MALLOC_CHAR(int n)
{
char *x;
x=(char*)malloc(n*sizeof(char));
if(x==NULL)
{
printf(“Insufficient memory\n”);
exit(0);
}
return x;
}
4) Allocating memory for double values

int* MALLOC_DOUBLE(int n)
{
double *x;
x=(double*)malloc(n*sizeof(double));
if(x==NULL)
{
printf(“Insufficient memory\n”);
exit(0);
}
return x;
}
The above functions have to be invoked appropriately as shown below:

Supriya C, Dept of ISE,AIT, Bangalore Page 20


P=MALLOC_INT(n);
Where n is the number of elements in array

Program Segment example1:


int *p;
p=MALLOC_INT(5);

above segment allocate 5 locations to store integer values. consider size of integer is 2 bytes so,
total 5*2 =10 bytes allocates for 5 integer values.

Program Segment example 2: allocate memory for n floating point numbers

float *p;
p=MALLOC_FLOAT(n);

Program Segment example 3: allocate memory for n characters

char *p;
p=MALLOC_CHAR(n);

It is not possible to write generalized function to allocate memory for n elements of any data type
in C. But it’s possible to write a generalized macro in place of generalized function.

Macro to allocate memory for one or more items of any data type using malloc

#define MALLOC(p,n,type) \
p=(type*)malloc(n*sizeof(type)); \
if(p==NULL) \
{ \
printf(“Insufficient memory\n”); \
exit(0); \

Supriya C, Dept of ISE,AIT, Bangalore Page 21


}

NOTE:
The symbol \ is an instruction given to the preprocessor that all the lines following \ are
continuation of the first line of that macro definition.

PROGRAM Example: program to add two numbers using macro MALLOC

#include<stdio.h>
#define MALLOC(p,n,type) \
p=(type*)malloc(n*sizeof(type)); \
if(p==NULL) \
{ \
printf(“Insufficient memory\n”); \
exit(0); \
}
main()
{
int *p1,*p2;
int sum;
MALLOC(p1,1,int);
MALLOC(p2,1,int);

*p1=10;
*p2=20;
sum=*p1+*p2;
printf(“%d+%d=%d\n”,*p1,*p2,sum);
}

Supriya C, Dept of ISE,AIT, Bangalore Page 22


Macro to allocate memory for one or more items of any data type using calloc
#define CALLOC(p,n,type) \
p=(type*)calloc(n,sizeof(type)); \
if(p==NULL) \
{ \
printf(“Insufficient memory\n”); \
exit(0); \
}
PROGRAM Example: program to add two numbers using macro CALLOC
#include<stdio.h>
#define CALLOC(p,n,type) \
p=(type*)calloc(n,sizeof(type)); \
if(p==NULL) \
{ \
printf(“Insufficient memory\n”); \
exit(0); \
}
main()
{
int *p1,*p2;
int sum;
CALLOC(p1,1,int);
CALLOC(p2,1,int);
*p1=10;
*p2=20;
sum=*p1+*p2;
printf(“%d+%d=%d\n”,*p1,*p2,sum);
}

Macro to reallocate memory for one or more items of any data type using realloc

Supriya C, Dept of ISE,AIT, Bangalore Page 23


#define REALLOC(p,n,type) \
p=(type*)realloc(p,n*sizeof(type)); \
if(p==NULL) \
{ \
printf(“Insufficient memory\n”); \
exit(0); \
}
PROGRAM Example: program to reallocate using macro REALLOC
#include<stdio.h>
#define REALLOC(p,n,type) \
p=(type*)realloc(p,n*sizeof(type)); \
if(p==NULL) \
{ \
printf(“Insufficient memory\n”); \
exit(0); \
}
void main()
{
Char *str;
str=(char*)malloc(15);
strcpy(str,”information”);
printf(“string=%s\n”,str);
REALLOC(str,60,char);
strcpy(str,”information science and Engineering”);
printf(“string=%s\n”,str);
}

Two-Dimensional Arrays using pointer to pointer

Supriya C, Dept of ISE,AIT, Bangalore Page 24


For multidimensional arrays the concept of array-of-arrays is used. A 2-dimensional array is
represented as a 1-dimensional array of pointers where each pointer contains address of one
dimensional array.
EX: To represent a 2-dimensional array int a[3][5]; we create a 1-dimensional array ‘a’ whose
length is 3; each element of ‘a’ is a 1-dimensional array whose length is 5.
The following shows the memory structure.

[0] [1] [2] [3] [4]

a[0]

a[1]

a[2]

The element a[i][j] is found by first accessing the pointer in a[i]. This gives the address of the
zero th element of row ‘i’ of the array. Then by adding ‘j’ to this pointer the address of the j th
element of row ‘i’ is found
This means,
 The expression *(a + i) + j points to the jth element in the ith row i.e. *(a + i) + j = &a[i][j]
 The expression *( *(a + i) + j ) gives the value of the element in i th row and jth column i.e.
*( *(a + i) + j ) = a[i][j].

A 2-dimensional array with 3 rows and 5mcolumns can be created by allocating the memory
dynamically in two stages.
Stage 1: Allocate memory for specified number of row pointers.
Example: allocate memory for 3 row pointers using: MALLOC(x,3,int*);
Pictorial representation is shown below

Supriya C, Dept of ISE,AIT, Bangalore Page 25


X[0]
3-rows X[1]
X[2]

In general
MALLOC(x,rows,int*); //rows-represents number of rows in a two dimensional array

Stage 2: Allocate memory for each row with specified number of column .
Example: Allocate memory for 5 columns with respect to row x[0],x[1] and x[2] using
MALLOC() three times as shown below.
[0] [1] [2] [3] [4]
X[0]
X[1]
X[2]

3-rows 5-columns

X[3][5]

Two-Dimensional Dynamic Arrays


Program to read and print an of ‘m X n’ matrix using dynamic arrays
#include<stdio.h>
void main( )
{
int rows, columns, i, j;
int **a;

printf(“Enter the number of rows in the matrix\n”);


scanf(“%d”, &rows);
printf(“Enter the number of columns in the matrix\n”);

Supriya C, Dept of ISE,AIT, Bangalore Page 26


scanf(“%d”, &columns);

// ALLOCATE MEMORY FOR ROWS


a = (int **) malloc(rows * sizeof(int *));
// FOR EACH ROW ALLOCATE MEMORY FOR COLUMNS
for(i = 0; i < rows; i++)
{
a[i] = (int *) malloc(columns * sizeof(int));
}

printf(“Enter the matrix elements\n”);


for( i = 0; i < rows ; i + + )
{
for( j = 0; j < columns ; j + + )
{
scanf(“%d”, *(a + i) + j ); // scanf(“%d”, &a[i][j] );

}
}
printf(“The entered the elements are\n”);
for( i = 0; i < rows ; i + + )
{
for( j = 0; j < columns ; j + + )
{
printf(“%d \t”, *( *(a + i) + j ) ); // printf(“%d \t”, a[i][j] );
}
printf(“\n”);
}
free(a);
}

Supriya C, Dept of ISE,AIT, Bangalore Page 27


Program to read and print an of ‘m X n’ matrix using dynamic arrays (using user defined
functions)
#include<stdio.h>
#include<stdlib.h>
#define MALLOC(p,n,type)\
p=(type*)malloc(n*sizeof(type));\
if(p==NULL)\
{\
printf("Insufficient memory!\n");\
exit(0);\
}
int** make(int rows, int cols)
{
int **x,i,j;
MALLOC(x,rows,int*);
for(i=0;i<rows;i++)
MALLOC(x[i],cols,int);
return x;
}
void read(int **a,int rows,int cols)
{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&a[i][j]);
}
}
void print(int **a,int rows,int cols)
{
int i,j;

Supriya C, Dept of ISE,AIT, Bangalore Page 28


for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
}
int main()
{
int rows, cols, **a;
printf("Enter the order of the matrix :");
scanf("%d%d",&rows,&cols);
a=make(rows,cols);
printf("Enter the elements :");
read(a,rows,cols);
printf("The elements are :");
print(a,rows,cols);
free(a);
return 0;
}
Program to add two matrices that are created dynamically
#include<stdio.h>
#include<stdlib.h>
#define MALLOC(p,n,type)\
p=(type*)malloc(n*sizeof(type));\
if(p==NULL)\
{\
printf("Insufficient memory!\n");\
exit(0);\
}
int** make(int rows, int cols)

Supriya C, Dept of ISE,AIT, Bangalore Page 29


{
int **x,i,j;
MALLOC(x,rows,int*);
for(i=0;i<rows;i++)
MALLOC(x[i],cols,int);
return x;
}
void read(int **a,int rows,int cols)
{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&a[i][j]);
}
}
void print(int **a,int rows,int cols)
{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
}
void add(int **a,int **b,int **c,int rows,int cols)
{
int i,j;
for(i=0;i<rows;i++)
{

Supriya C, Dept of ISE,AIT, Bangalore Page 30


for(j=0;j<cols;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
int main()
{
int rows, cols, **a,int **b,int **c;
printf("Enter the order of the matrix :");
scanf("%d%d",&rows,&cols);
if(rows<0||cols<0)
{
printf(“Invalid matrix size\n”);
exit(0);
}
a=make(rows,cols);
printf("Enter the elements :");
read(a,rows,cols);
b=make(rows,cols);
printf("Enter the elements :");
read(b,rows,cols);
c=make(rows,cols);
add(a,b,c,rows,cols);
printf(“sum of two matrices\n”);
print_array(c,rows,cols);
free(a);
free(b);
free(c);
return 0;
}

Supriya C, Dept of ISE,AIT, Bangalore Page 31

You might also like