Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
82 views17 pages

Without This Message by Purchasing Novapdf : Print To PDF

The document discusses pointers in C programming. It defines pointers as variables that contain the memory address of another variable. It covers pointer declaration and initialization, using the address and dereference operators, and assigning values to pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views17 pages

Without This Message by Purchasing Novapdf : Print To PDF

The document discusses pointers in C programming. It defines pointers as variables that contain the memory address of another variable. It covers pointer declaration and initialization, using the address and dereference operators, and assigning values to pointers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER - 7

Pointers

7.1 Introduction
Pointers are one of the powerful and a frequently used feature of C. Pointer is a variable that
contain the memory address of another variable. Variables contain the values and pointer variables
contain the address of variables that has the value. Variable directly references the value and
Pointer variable indirectly references the value. Referencing a value through a pointer is called
indirection. The pointer has the following advantages.
 The pointer enables us to access a variable that is defined outside the function.
 The pointer is more efficient in handling the data tables.
 It reduces the length and complexity of a program.
 It allows passing variables arrays, functions, strings and structures as function arguments.
 A pointer allows returning structures variables from functions.
 It provides functions, which can modify their calling arguments.
 It supports dynamic allocations and de-allocations of memory segments
 Pointer can return more than one value.
 A pointer improves the efficiency of certain routines.

For example: int i=3;


i = variable name 3 = value at variable location
Let 6251 = memory address of the variable (i.e. local, structure,
pointer, union variable etc.)

7.2 Pointer Declaration and Initialization


A pointer variable is declared with an asterisk before the variable name. The type-specifier
determines that what kind of variable the pointer variable points to.

Declaration
Syntax: data-type *pointer_variable_name;

Pointer operator
C provides two operators, & and *, for pointer implementation, which are inverse of each other.
& (Ampersand) operator * (Asterisk) operator
 Address of operator. It is a unary  Value at address or Indirection or de-
operator that returns the address of its referencing operator. It returns the value
operand. of the variable to which its operand
 Synatax: data_type points.
*pointer_variable_name;  Syntax: pointer_variable =
&general_variable
 For example: int *myptr;  For example: mypter=&x;

Initialization
Pointer variables should be initialized to 0, Null or an address. No other constant can be initialized
to a pointer variable. Pointer variable of a particular data type can, hold only the address of the
variable of same data type. For example:
Valid Invalid
int a , b , *p = &a , *q = NULL; b = &a; //Ordinary variables cannot hold address.
q = p; // Both p and q is pointing to the q = a; //cannot assign value to the pointer
memory location of variable a variable.

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 1

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


For example:
#include <stdio.h> x ptr
#include <conio.h>
void main() 10 1310548
{
1310548 1310544
int x=10;
int *ptr;
ptr=&x;
printf("\n Address of x = %u", &x);
printf("\n Address of x =%u",ptr);
printf("\n Address of ptr = %u", &ptr);

printf("\n Value of x = %d", x);


printf("\n Value of x = %d", *ptr);
printf("\n Value of ptr = %d", ptr);

getch(); Output:
} Address of x = 1310548
Address of x = 1310548
Address of ptr = 1310544
Value of x = 10
Value of x = 10
Value of ptr = 1310548

Note:

Representation Description
int *p The pointer variable p is integer type pointer. In other word, p is capable to
hold the value of integer type variable.
int *p[10] p as an array of 10 pointers
int (*p)[10] p as a pointer to a set of one dimensional array of 10 elements.
int (*p) (void) p is a function that return a pointer to an integer quality.
int *p (char *a) p is a function that accept an argument which is a pointer to a character and
return a pointer to an integer quality.

7.3 Pointer assignment


A pointer is a variable data type and hence the general rule to assign its value to the pointer is same
as that of any other variable data type. For example:
int x, y;
int *ptr1,*ptr2;

Operation Description
ptr1=&x; The memory address of variables x is assigned to the pointer variable ptr1.
y=*ptr1; The contents of the pointer variables is assigned to the variable y (i.e. value of
x), not the memory address (i.e. y = ptr1 is impossible)
ptr2=ptr1; Address if ptr1 is assigned to the ptr2. The contents of both ptr1 and ptr2 will
be same as these two pointer variables hold the same address

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 2

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Examples:

 WAP to assign a character variable to the pointer and to display the contents of the
pointer.
#include<stdio.h>
#include <conio.h> Output:
void main() Value of x = c
{ Pointer value ptr = c
char x,y;
char *ptr;
clrscr();
x='c'; /*assignment of character*/
ptr=&x;
y=*ptr;
printf("Value of x = %c",x);
printf("\nPointer value ptr = %c",y);
getch();
}

 WAP for assignment and usage of & operator.

Example-1:
#include <stdio.h>
#include <conio.h> Output:
void main() Address of i= 1310548
{ Value of i = 3
int i=3; Value of i using *(&i)= 3
clrscr();
printf("Address of i=%d",&i);
printf("\nValue of i = %d",i);
printf("\nValue of i using *(&i)=%d",*(&i));
getch();
}

Example-2:
#include <stdio.h>
#include <conio.h>
void main()
{
int *j,k=5;
j=&k;
clrscr();
Output:
printf("Address of k=%d",&k); Address of k=1310544
printf("\nAddress of k=%d",j); Address of k=1310544
printf("\nAddress of j=%d",&j); Address of j=1310548
printf("\nValue of j=%d",j); Value of j=1310544
printf("\nValue of k=%d",k); Value of k=5
printf("\nValue of k=%d",*(&k)); Value of k=5
printf("\nValue of k=%d",*j); Value of k=5
getch();
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 3

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Example-3:
#include <stdio.h>
#include <conio.h>
void main()
{ int p=10,*q,**r;
q=&p;
r=&q;
clrscr();
printf("Address of p=%d",&p); Output:
printf("\nAddress of p=%d",q); Address of p=1310548
printf("\nAddress of p=%d",*r); Address of p=1310548
printf("\nAddress of q=%d",&q); Address of p=1310548
printf("\nAddress of q=%d",r); Address of q=1310544
printf("\nAddress of r=%d",&r); Address of q=1310544
printf("\nValue of q=%d",q); Address of r=1310540
printf("\nValue of r=%d",q); Value of q=1310548
printf("\nValue of p=%d",p); Value of q=1310548
printf("\nValue of p=%d",*(&p)); Value of p=10
printf("\nValue of p=%d",*q); Value of p=10
printf("\nValue of p=%d",**r); Value of p=10
getch(); Value of p=10
}

7.4 Pointer Arithmetic


As a pointer holds the memory address of variable, some arithmetic operations can be performed
with pointers. C and C++ support four arithmetic operators that can be used with pointers, such as:
Pointer arithmetic Operator Symbol
Addition +
Subtraction -
Increment ++
Decrement --

Pointer is variables that hold that memory address of another variable. They are not integers, but
they can be displays as unsigned integers. According to data type declared to that pointer variable
if arithmetic operation is done then values (contents) will be incremented or decremented as per
the data type is chosen.
Let p = &a[0] = 1001 i.e. Base address of an array
int type pointer float type pointer char type pointer
(2-byte space) (4-byte space) (1-byte space)
p++ = p+1 = 1001 + 2 = 1003 p++ = 1001 + 4 = 1005 i.e. p++ = 1001 + 1 = 1002 i.e.
i.e. Address of next element Address of next element Address of next element
p = p+5 = 1001 + 10 = 1011 p = p+5 = 1001 + 20 = 1021 p = p+5 = 1001 + 5 = 1006 i.e.
i.e. Address of 5th integer type i.e. Address of 5th float type Address of 5th char type
element. element. element.
Note: Same operation is done for decrement.

Invalid pointer operation


 Addition of two pointer
 Addition or subtraction of float or double data type to or from a pointer.
 Multiplication of pointer with a constant.
 Division of two pointer or with a constant
Example: Illegal operations: p1/p2 p1*p2 p1+p2 p1/5
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 4

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Examples:

 WAP to increment the pointer’s address.


#include <stdio.h>
#include <conio.h>
void main()
{
float value,*ptr;
Output:
value=120;
ptr=1310548
clrscr(); ptr=1310552
ptr=&value;
printf("ptr=%u",ptr);
ptr++;
printf("\nptr=%u",ptr);
getch();
}

 WAP to show the arithmetic operation on pointers.

Example-1:
#include <stdio.h>
#include <conio.h>
void main()
{
float value,*ptr;
int x,*ptr1,*ptr2;
clrscr();
value=120.0;
ptr=&value;
printf("\nMemory address=%d",ptr);
ptr++;
printf("\nMemory address after increment=%d",ptr);
ptr--;
printf("\nMemory adderss after decrement=%d\n\n\n",ptr);
x=101;
ptr1=&x;
printf("ptr1=%d",ptr1);
ptr2=ptr1+6;
printf("\nValue of x=%d",x);
printf("\nCotents of ptr1=%d",*ptr1);
printf("\nAddress of ptr1=%d",&ptr1);
printf("\nAddress of (ptr2=ptr1+6)=%d",&ptr2);
printf("\nAddress of ptr2=%d",*ptr2); /*Any garbage value*/
getch();
}

Example-2:
#include <stdio.h> Output:
#include <conio.h> Value of x=10 and pointer=10
void main() Value of y=11 and pointer=11
{
int x,y,*ptr;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 5

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


clrscr();
x=10;
ptr=&x;
printf("Value of x=%d and pointer=%d",x,*ptr);
y=++ *ptr; /*y=11*/
printf("\nValue of y=%d and pointer=%d",y,*ptr);
getch();
}

Example-3:
#include <stdio.h>
#include <conio.h>
void main()
{
int x,y,*x_pointer,temp;
clrscr();
temp=3;
x=5*(temp+5); Output:
x_pointer=&temp; x =40
y=6*(*x_pointer+5); y = 48
printf("x=%d",x);
printf("\ny=%d",y);
getch();
} Output:
 Contents of pointer=25
 Value of y=26 and pointer
Example-4: (*ptr=*ptr+1)= 26
#include <stdio.h>
 Value of y=27 and pointer
#include <conio.h>
(*ptr)++=27
void main()
 Value of y=28 and pointer ++
{
*ptr =28
int x,y,*ptr,*ptr2;
clrscr();  nPointer *ptr=29
x=25;  Pointer *ptr2=29
ptr=&x;
printf("Contents of pointer=%d",*ptr);
*ptr=*ptr+1; // ++*ptr
y=*ptr;
printf("\nValue of y=%d and pointer
(*ptr=*ptr+1)=%d",y,*ptr);
(*ptr)++;
y=*ptr;
printf("\nValue of y=%d and pointer (*ptr)++= %d",y,*ptr);
++ *ptr;
y=*ptr;
printf("\nValue of y=%d and pointer ++ *ptr = %d",y,*ptr);
++ *ptr;
ptr2=ptr;
printf("\nPointer *ptr=%d",*ptr);
printf("\nPointer *ptr2=%d",*ptr2);
getch();
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 6

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


7.5 Pointers and Functions
Pointers are very much used in function declaration. Sometimes only with a pointer a complex
function can be easily represented and accessed. The use of the pointers in a function definition
may be classified into two groups they are call by value and call by reference, as described in
previous chapter.

Call by value Call by Reference


#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
void swap (int, int); void swap (int *x, int *y);
void main() void main()
{ int x=100,y=20; { int x=100,y=20;
clrscr(); clrscr();
printf("Values before printf("Values before
swap\n"); swap\n");
printf("x=%d y=%d",x,y); printf("x=%d y=%d",x,y);
swap(x, y); swap(&x,&y);
getch(); printf("\nValues after
} swap\n");
printf("x=%d y=%d",x,y);
void swap(int a,int b) getch();
{ int temp; }
temp=a;
a=b; void swap(int *a,int *b)
b=temp; { int temp;
printf("\nValues after temp=*a;
swap\n"); *a=*b;
printf("x=%d y=%d",a,b); *b=temp;
} }
Output: Output:
Values before swap Values before swap
x=100 y=20 x=100 y=20
Values after swap Values after swap
x=20 y=100 x=20 y=100
In CALL BY VALUE method, the called In CALL BY REFERENCE method, the
function creates its own copies of the called function accesses and works with the
original values sent to it. Any changes, that original values using their references. Any
are made, occur on the called function's copy changes, that occur, take place on the original
of values and are not reflected back to the values and are reflected back to the calling
calling function. code.

Returning multiple values from function using pointer


The use of return() function, we can return only one value but it is unable to return more than
one value at a time. This operation can be possible using pointer in the function by “call by
reference” method.

For example:
#include <stdio.h>
#include <conio.h>
void fun (int redious, float *area, float *perimeter);
void main()
{ int redious;
float area, perimeter;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 7

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


clrscr();
printf("Enter redious of circle:");
scanf ("%d", &redious);
fun(redious, &area,&perimeter);
printf("\nArea = %f", area);
printf("\nPerimeter=%f",perimeter);
getch();
}

void fun(int r, float *a, float *p)


{ *a=3.14*r*r;
*p=2*3.14*r;
}

7.6 Pointers and Arrays


Arrays Pointers
Array is used to store the similar data items in Pointer addressing is in the form of
contiguous memory locations under single name. absolute addressing. Exact location
Array addressing is in the form of relative addressing. of the elements can be accessed
Compiler treats the subscript as a relative offset from directly by assigning the starting
the beginning of the array. Array subscripting notation location of the array to the pointer
is converted to pointer notation during compilation, so variable. The pointer variable is
writing array subscripting expressions using pointer incremented to find the next
notation can save compile time. element.

For example-1: A program to access the array element using pointer.


#include <stdio.h>
#include <conio.h> Output: 1 2 3 4 5
void main()
{ int myArray[5]={1,2,3,4,5};
int i;
clrscr();
for(i=0;i<5;i++)
printf("%d\t",*(myArray+i));
getch();
}

Example-2:
int a[5] = {1,2,3, 4,5} , *ptr , i ;
ptr = a ; // similar to ptr = &a[0];
Assume that array starts at location 1000
&a[0] = 1000 a[0] = 1 ptr + 0 = 1000 *(ptr+0) = 1
&a[1] = 1002 a[1] = 2 ptr + 1 = 1002 *(ptr+1) = 2
&a[2] = 1004 a[2] = 3 ptr + 2 = 1004 *(ptr+2) = 3
&a[3] = 1006 a[3] = 4 ptr + 3 = 1006 *(ptr+3) = 4
&a[4] = 1008 a[4] = 5 ptr + 4 = 1008 *(ptr+4) = 5
Accessing value Accessing address
printf (“%d “,*(ptr+i)); // displays the a[i] value printf (“%u “, (ptr+i)); // displays address
printf (“%d “,*ptr); //displays the a[0] value of a(i)
printf (“%d “,*(a+i)); // displays the a[i] value

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 8

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


For example-2: A program to access the array element and particular memory location using
pointer.
Without using pointer Using pointer
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
void main() void main()
{ int x[]={10,20,30,40,50}; { int x[]={10,20,30,40,50};
int i; int i, *p;
clrscr(); p = &x[0];
for(i=0;i<5;i++) clrscr();
printf("\nArray element = for(i=0;i<5;i++)
%d\t and Memory location = {
%u", x[i], &x[i]); printf("\nArray element = %d\t
getch(); and Memory location = %u", *p, p);
} p = p+1;
}
getch();
}

Array of pointer (Pointer variables)


As in above program, we cannot increment the pointer constant but the pointer variable can be
incremented as shown in following figure. While we can’t increment an address, we can increment
a pointer that holds an address.

For example-1:
#include <stdio.h>
#include <conio.h>
void main()
{
int myArray[]={1,2,3,4,5};
int *ptr2myArray,i;
clrscr();
ptr2myArray=myArray;
for(i=0;i<5;i++)
printf("%d\t",*(ptr2myArray++));
getch();
}

Output: 1 2 3 4 5

For example-2:
#include <stdio.h>
#include <conio.h>
void main()
{
int *A[3];
int x, y, z;
x=2; y=5; z=6;
printf ("\t");
A[0] = &x;
A[1] = &y;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 9

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


A[2] = &z;
clrscr();

for(int i=0;i<=2;i++)
{
printf("%u\t",A[i]);
printf("%d\t",*A[i]);
}
getch();
}

Output: 1310548 2 1310544 5 1310540 6

 WAP to display the contents of 2-Dimensional array using pointer arithmetic.


#include <stdio.h>
#include <conio.h>
void main()
{ int a[2][3]={
{11,12,13},
{14,15,16}
};
int *ptr;
int i,j,n,temp;
clrscr();
printf("Contents of the array\n");
for(i=0;i<=1;i++)
{
for(j=0;j<=2;j++)
{
temp=*(*(a+i)+j);
printf("%d\t",temp);
}
}
getch();

Note: Pointer to pointer value exchange is called double indirection.

Passing arrays using pointers


As we passed the variables onto the function based using pointer in the same way arrays are passed
as arguments to functions and their elements being access by the function. However, it’s more
common to use pointer notation instead of array notation when arrays are passed to the function.

For example:
#include <stdio.h>
#include <conio.h>
#define MAX 5
void multiply_array(int *myArray);
void main()
{
int myArray[MAX]={10,12,14,16,18},j;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 10

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


clrscr();
multiply_array(myArray);
for(j=0;j<MAX;j++)
printf("myArray[%d]:%d\n",j,myArray[j]);
getch();
}

void multiply_array(int *ptr)


{
int j;
for(j=0;j<MAX;j++)
*ptr++ *=2; /*here ptr points to elements of myArray*/
}

Pointers and strings


Using pointer to the array and then using pointer arithmetic usually perform many string
operations in C and C++. As strings tend to be accesses strictly in sequential order, pointers use the
obvious choice. Strings are one-dimensional arrays of type char. In C and C++, a string is
terminated by NULL or ‘\0’. String constants are written in double quotes.

For example:
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
void output(char *s);
void main()
{
char s[20];
clrscr();
printf("Enter a word:");
scanf("%s",s);
printf("\nOutput:");
output(s);
getch();
}

void output(char *ptr)


{
while(*ptr!=NULL)
{
printf("%c",*ptr);
ptr++;
}
}

Pointer to string constant


Here, the pointer points to string constant. Pointer is increased by whom the value is holding.

For example:
#include <stdio.h>
#include <conio.h>
void main()
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 11

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


{
char str1[]="This is a string stored in an array";
char *str2="This is string stored using pointer";
clrscr();
printf("%s",str1);
printf("\n%s",str2);
str2+=5;
printf("\n%s",str2);
getch();
}
Output:
This is a string stored in an array
This is string stored using pointer
is string stored using pointer

 WAP to store character in the array.


#include <stdio.h>
#include <conio.h>
void output(char *ptr);
void main()
{ char s[]="I\'m string stored in an array";
clrscr();
output(s);
getch();
}

void output(char *ptr)


{
while(*ptr)
{
printf("%c",*ptr++);
}
}

Output: I'm string stored in an array

 WAP to copy string form one array to another array.


#include <stdio.h>
#include <conio.h>
void CopyString(char *dest, char *src);
void main()
{
char source[20],destination[20];
clrscr();
printf("Enter the string:");
scanf("%s",source);
CopyString(destination,source);
printf("%s",destination);
getch();
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 12

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


void CopyString(char *dest, char *src)
{
while (*src!='\x0')
*dest++=*src++;
*dest='\x0';
}

 WAP to display the name of days stored on the array of pointer.


#include <stdio.h>
#include <conio.h>
void main()
{ char *ptr2array[7]={
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
int j;
clrscr();
for(j=0;j<7;j++)
printf("%s\n",ptr2array[j]);
getch();
}

 WAP to demonstrate the usage of printing character at a time and using loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int x[5]={1,2,3,4,5};
char d[]={'A','P','P','L','E','\0'};
clrscr();
for(int i=0;i<5;i++)
{
Output:
printf("%d\t",x[i]); 1 2 3 4 5
} APPLE
printf("\n\n");
printf("%s",d);
getch();
}

NOTE:
Pointers and Multi-Dimensional Arrays
As the internal representation of a multi-dimensional array is also linear, a pointer variable can
point to an array of any dimension. The way in which the pointer variable used, varies according to
the dimension.
General Form: ptr_vble = &array_name [index1]…[ indexn]; OR
ptr_vble = array_name;
Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 13

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Example
int a[2][2] = {1,2,3,4} , *ptr ;
ptr = &a[0][0] ;
Assume that the array starts at location 1000
&a[0][0] = 1000 a[0][0] = 1 ptr+0 = 1000 *(ptr+0) = 1
&a[0][1] = 1002 a[0][1] = 2 ptr+1 = 1002 *(ptr+1) = 2
&a[1][0] = 1004 a[1][0] = 3 ptr+2 = 1004 *(ptr+2) = 3
&a[1][1]=1006 a[1][1]=4 ptr+3=1006 *(ptr+3) = 4

If the pointer to the array is accessed with 2 subscripts, it results in a problem. For example,
 (p+0) + 1 // if it is used to represent 0th row and 1st column and
 (p+1) + 0 // if it is used to represent 1st row and 0th column results in p+1.

So, multi-dimensional arrays can be represented by pointer in the following two ways:
 Pointer to a group of arrays
 Array of pointers

A. Pointer to a group of arrays


A two dimensional array, for example, is a collection of one dimensional array. Therefore, a
two-dimensional array is defined as a pointer to a group of one dimensional array and in the
same way three dimensional arrays can be represented by a pointer to a group of two
dimensional arrays. The int a[3][2] can be represented by a pointer as follows:
int (*p)[2] p is a pointer points to a set of one dimensional array, each with 2 elements.
First dimension need not be specified but the second dimension has to be specified. Here, a
single pointer is used and it needs to know how many columns are there in a row.
The following representations are used when a pointer is pointing to a 2D array:
 ptr+i is a pointer to ith row.
 *(ptr+i) refers to the entire row - actually a pointer to the first element in ith row.
 (*(ptr + i) +j) is a pointer to jth element in ith row
 *(*(ptr+i) + j)) refers to the content available in ith row, jth column

Example: Accessing value


printf (“%d “,*(*(ptr + i) +j); // displays the x(i, j) value
printf (“%d “,*(a[ i ] + j); // displays the x(i, j) value
printf (“%d “,*(a + i)[ j ]; // displays the x(i, j) value

B. Array of Pointers
Multi-dimensional array can also be expressed in terms of an array of pointers. The int
a[2][2] can be represented as int *ptr[2]; Here, we have 2 pointers ptr[0], ptr[1] and
each pointer can point to a particular row . Thus, only one indirection is enough to represent a
particular element.

Example
int a[2][2] = {1,2,3,4} , *ptr[2] ;
ptr[0] = a[0]; /* ptr[0] is now pointing to the 0th row ( & a[0][0]) */
ptr[1] = a[1]; /* ptr[1] is now pointing to the 1st row ( & a[1][0]) */
ptr[0] + 0 = 1000 *(ptr[0] + 0) = 1
ptr[0] + 1 = 1002 *(ptr[0] + 1) = 2
ptr[1] + 0 = 1004 *(ptr[1] + 0) = 3
ptr[1] + 1 = 1006 *(ptr[1] + 1) = 4

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 14

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


7.7 Dynamic Memory Allocation
The programmer uses the in-build function of stdlib.h for dynamic memory allocation. The
function calloc() and malloc() used to create the space for array, structure, and union dynamically.
The difference in malloc and calloc is that malloc does not set the memory to zero whereas calloc
sets allocated memory to zero. If there is no reason to initialize the array to zero, then the use of
either calloc() or malloc() is acceptable. Generally, the malloc() takes less time.

A. Function: malloc ()
The C library function void *malloc(size_in_bytes) allocates the requested
memory and returns a pointer to it.

Syntax: void *malloc (size_in_bytes);


This function returns a pointer to the allocated memory, or NULL if the request fails.

Example-1: malloc () for string function


#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free, rand */
#include <string.h>
#include <conio.h>
int main()
{ char *str;
str = (char *) malloc(15); /* Initial memory allocation */
strcpy(str, "NAST");
printf("String = %s, Address = %u\n", str, str);
str = (char *) realloc(str, 25); /* Reallocating memory */
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
getch(); Output:
return(0); String = NAST, Address = 355090448
} String = NAST.com, Address = 355090448

Note: Here, (char *) before the malloc() and realloc() function is used to convert
(void *) to (char *) because the function is of void type.

Example-2: malloc () for structures


#include<stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct rec
{ int i;
float PI;
char A;
}RECORD;

int main()
{ RECORD *ptr_one;
ptr_one = (RECORD *) malloc (sizeof(RECORD));
(*ptr_one).i = 10;
(*ptr_one).PI = 3.14;
(*ptr_one).A = 'a';
printf("First value: %d\n",(*ptr_one).i);

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 15

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


printf("Second value: %f\n", (*ptr_one).PI);
printf("Third value: %c\n", (*ptr_one).A);
free(ptr_one);
getch();
Output:
return 0;
First value: 10
}
Second value: 3.140000
Third value: a

B. Function: calloc()
The C library function allocates the requested memory and returns a pointer to it.

Syntax:
void *calloc (number_of_blocks, size_of_each_block_in_bytes);

This function returns a pointer to the allocated memory, or NULL if the request fails.

For example: a = calloc (n, sizeof (int)); This allocates contiguous space in
memory for an array of n-elements with each element having 2-byte memory (since for int).
Here ‘a’ is an array variable.

For example, an int array of 10 elements can be allocated as follows:


int * array = (int *) calloc (10, sizeof (int));

Note that this function can also malloc, written as follows.


int * array = (int *) malloc (sizeof (int) * 10);

Example-1: calloc () function Output:


#include <stdio.h> Number of elements to be entered:3
#include <stdlib.h> Enter 3 numbers:
#include <conio.h> 22
int main() 55
{ 14
int i, n; The numbers entered are: 22 55 14
int *a;
printf("Number of elements to be entered:");
scanf("%d",&n);
a = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ )
{
scanf("%d",&a[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ ) {
printf("%d ",a[i]);
}
getch();
return(0);
}

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 16

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)


Example-2: calloc () function to allocate memory storage space dynamically.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
unsigned num;
int *ptr;
printf("Enter the number of type int to allocate: ");
scanf("%d", &num);
ptr = (int*)calloc(num, sizeof(int));
if (ptr != NULL)
puts("Memory allocation was successful.");
else
puts("Memory allocation failed.");
getch();
return(0);
}

Output:
Enter the number of type int to allocate: 100
Memory allocation was successful.
Enter the number of type int to allocate: 99999999
Memory allocation failed.

malloc () calloc ()
1. The term malloc stands for memory 1. The term calloc stands for contiguous
allocation. allocation.
2. The malloc is dynamic memory allocation 2. The calloc is similar to malloc but only
it allocates the memory and initializes difference is initialize zero
garbage value.
3. malloc create the memory space 3. calloc calculate the memory space
4. malloc take one argument i.e. 4. calloc take two argument i.e.
(malloc(sizeof(int)*10) and allocate bytes (calloc(no.of.var, size of each var) and
of memory. allocate block of memory.
5. malloc allocates memory as a single 5. calloc allocates memory which may/may
contiguous block. not be contiguous.
6. if a single contiguous block cannot be 6. it follows from point 2 that calloc will not
allocated then malloc would fail. fail if memory can be allocated in non-
contiguous blocks when a single
7. No need to free the memory explicitly contiguous block cannot be allocated
while using malloc. Variables used with 7. But one needs to free the memory
malloc are destroyed automatically explicitly while variables are created using
calloc
8. malloc allocates memory requests size of 8. malloc allocates memory requests size of
bytes and returns a pointer to the 1st byte of bytes and returns a pointer to the 1st byte
allocated space of allocated space

Programming in C - Compiled by Yagya Raj Pandeya, NAST, Dhangadhi ©[email protected] Page 17

Print to PDF without this message by purchasing novaPDF (http://www.novapdf.com/)

You might also like