Lesson11 Pointers
Lesson11 Pointers
Chapter Outline
Chapter Outline
“Better pointed bullets than pointed words.”
-Otto Von Bismarck Introduction.
Introduction.
Advantages of pointers.
Advantages of pointers.
Referencing operator.
Referencing operator.
De-referencing operator.
De-referencing operator.
Working with pointers.
Working with pointers.
Operations on pointers.
Operations on pointers.
Pointers and functions.
Pointers and functions.
“If you open up the mind, the opportunity to
Casting pointers.
address both profits and social conditions are Casting pointers.
limitless. It's a process of innovation.” Dynamic memory
Dynamic memory
-Jerry Greenfield
allocation.
allocation.
Pointers and one-
Pointers and one-
dimensional numeric
dimensional numeric
arrays.
arrays.
Pointers and two-
Pointers and two-
“In all pointed sentences some degree of accuracy dimensional numeric
dimensional numeric
must be sacrificed to.” -Oscar Wilde arrays.
arrays.
Pointers and strings.
Pointers and strings.
Pointers and const.
Pointers and const.
Command line
Command line
arguments.
arguments.
Various pointer
Various pointer
declarations.
declarations.
Problems with pointers.
Problems with pointers.
Conclusion.
Conclusion.
11.1. Introduction
The smallest piece of data in computer memory is known as a bit, which represents 0 or 1. Bits are
grouped to form a byte. Bytes are grouped to form a word. Sets of one or more bytes are used to store
data items. Each byte in the computer memory is called memory location or memory cell. Computer
memory consists of a series of consecutive memory locations. Each memory location is numbered to be
referenced. The number attached to a memory location is called the memory address of that location.
This memory location is merely a positive number, usually a hexa decimal number.
C uses byte as the fundamental unit of data storage to measure the memory required for storing
the data items. A data item may require more than one byte. The number of bytes required for storing the
value of each data type is system dependent. When more than one byte are used for holding a value, the
starting address of that storage is considered as the address of that value (or data item).
Interview question #1
What is a pointer?
A Pointer is a special type of variable that holds the address as a data item in it. The address may be of
one of these: variable, array, function, structure or another pointer.
Usually, an ordinary variable holds a number or a character as a data item in it. Instead, pointer
holds the address. If a variable occupies more than one byte, pointer holds the first byte (or byte0)
address. As this is a variable, the address in a pointer can be changed. Mostly, pointer uses 2 or 4
bytes to hold the addresses. In short, a pointer variable is a group of cells that can hold an address.
Point to ponder #1
Pointer is just an address; not any ordinary value
The & operator should be preceded with the operand in order to return the address.
&Operand_1
a Name of variable
From this memory map, it is clear that the data item 20 can be accessed with the help of name of variable
as well as address of variable (or memory location or reference).
The conversion character %x is used to print address in hexa-decimal notation. The conversion
character %u is used to print the address in decimal notation (especially, a positive number to
understand easily).
Interview question #2
What are the differences between referencing operator and bitwise AND?
*Operand_1
Interview question #3
What are the differences between Indirection operator and Arithmetic operator?
Declaration of a pointer variable: Just like an ordinary variable, a pointer variable should be declared
before it is used. This declaration has the following form:
In this syntax,
<storage_class> is any one of the auto, static, extern or register.
<data typte> is any one of int, float, char, double or void or data types such as signed int, long int etc,
The symbol * should be preceded with the name(s) of pointer(s).
<pointer_name> is any valid identifier. If there are more pointer_names, those should be separated with
commas.
Ex: int *iptr; //pointer-to-int
float *fptr; //pointer-to-float
char *cptr; //pointer-to-char
Initialization of a pointer variable: A pointer variable should be initialized with an address before it is
used. The initialization of a pointer variable takes the following form:
Lvalue=Rvalue;
Where Lvalue is any pointer variable and Rvalue is a variable preceded with an ampersand or a pointer of
same type of LValue.
Point to ponder#2
A Pointer can never be initialized with a normal value (except 0); it should be initialized with an
address.
iptr1 a iptr2
Interview question #4
Interview question #5
What is a NULL pointer?
NULL pointer is a special type of pointer with the meaning: “not allocated” or “not pointing anywhere
yet”. That is, it points definitively nowhere; it is not the address of any variable, array, structure or
function.
If any type of pointer is initialized with the value 0, then it can be treated as a NULL pointer. The
following are the examples of NULL pointers:
1) int *iptr=0; 3) # define NULL 0 int *iptr=NULL;
2) float *fptr=0; 4) float *fptr=NULL;
In the example 4, NULL is a predefined macro that is available in stdio.h and stddef.h which has the
value 0 (same as example3).
Program #3
Write a program to declare, initialize and access a pointer variable
#include<stdio.h>
main()
{
int a=40;
int *iptr; //Declaration: pointer-to-int
iptr=&a; //Initialization: with the address of a
Pointer Description
Expression
Ptr=Ptr+n*sizeof(data_type_of_pointer)
Ptr+n Use the original value of ptr and then n*sizeof(data_type_of_pointer) is added
to ptr after statement execution.
Ptr=Ptr-n*sizeof(data_type_of_pointer)
Ptr-n Use the original value of ptr and then n*sizeof(data_type_of_pointer) is
subtracted from ptr after statement execution.
Ptr=Ptr+ sizeof(data_type_of_pointer)
Ptr++ Use the original value of ptr and then ptr is incremented after statement
execution.
Ptr=Ptr- sizeof(data_type_of_pointer)
Ptr-- Use the original value of ptr and then ptr is decremented after statement
execution.
Ptr=Ptr+ sizeof(data_type_of_pointer)
++Ptr
Original Ptr is incremented before the execution of statement.
Ptr=Ptr- sizeof(data_type_of_pointer)
--Ptr
Original Ptr is decremented before the execution of statement.
*(Ptr++)
*Ptr++ Retrieve the content of the location pointed to by pointer and then increment
ptr.
*(Ptr--)
*Ptr-- Retrieve the content of the location pointed to by pointer and then decrement
ptr.
*(++ptr)
*++Ptr Increment pointer and then retrieve the content of the new location pointed to
by Ptr.
*(--Ptr)
*--Ptr Decrement pointer and then retrieve the content of the new location pointer
to by Ptr.
Retrieve the content of *Ptr of the location pointed to by Ptr, and then
(*Ptr)++ Increment content of the location pointed to by Ptr. For pointer type content,
use pointer arithmetic of standard arithmetic.
Retrieve the content *Ptr of the location pointed to by Ptr, then decrement the
(*Ptr)--
content of that location; Ptr is not changed.
Point to ponder#4
Comparing two pointers those point to different types of objects lead to error, although they have
addresses as data items in them.
Point to ponder#4
Indirectly, a called function can return multiple values if pointers to these are passed as arguments.
Program #6
Write a program to interchange two numbers in calling function from called function
#include<stdio.h>
void swap(int *,int *); //function prototype
main()
{
int a,b,*aptr,*bptr;
printf(“\nEnter any two numbers:”);
scanf(“%d%d”,&a,&b);
aptr=&a;
bptr=&b;
printf(“\n Before swap a=%d\tb=%d”,a,b);
swap(aptr,bptr); //function call
printf(“\n After swap a=%d\tb=%d”,a,b);
}
void swap(int *x,int *y) //function definition
{
*x=*x+*y;
*y=*x-*y;
*x=*x-*y;
}
Output:
Output:
Enter the values of a and b: 10
12
The result=22
Output:
Enter the values of a and b: 10
12
The result=22
1) While calling the host function, place the name of the guest function as an argument. The name
itself serves as a pointer to guest function.
2) Give the definition of guest function as usual.
3) In the definition of host function, place a pointer to guest function as an argument.
4) In the definition of host function, call guest function for further process.
Program #9
Write a program that demonstrates function as an argument to another function
#include<stdio.h>
int add(int,int); //guest function prototype
void swap(int(*)(int,int));//host function prototype
int a,b;
main()
{
printf("\n Enter any two numbers:");
scanf("%d%d",&a,&b);
swap(add); //step-1
printf("\n After swap a=%d\tb=%d",a,b);
}
int add(int x,int y) //step-2
{
return x+y;
}
void swap(int (*addptr)(int,int)) //step-3
{
a=(*addptr)(a,b); //step-4
b=(*addptr)(a,-b); //step-4
a=(*addptr)(a,-b); //step-4
}
Output:
Enter any two numbers: 32
45
After swap a=45 b=32
In this syntax, ptr2 is a pointer variable of a data type that is going to be converted to the type of ptr1.
Usually, the <data type> is same as the type of <ptr1>.
Program #10
Write a program that demonstrates casting from one type to another
#include<stdio.h>
main()
{
int a=65;
int *iptr=&a;
char *cptr;
cptr=(char *)iptr;
printf("%c",*cptr);
}
Output:
A
Points to ponder #5
The limit for dynamic memory allocation can be as large as the amount of available physical memory in
the computer or the amount of available virtual memory in a virtual memory system.
C supports many built-in standard library functions for efficient dynamic memory allocation / de-allocation.
Their prototypes are declared in the header files stdlib.h, alloc.h and malloc.h. These functions are:
malloc(), calloc(), realloc() and free().
Though the value 0 is not a negative integer, malloc(0) does not return pointer to 0 bytes or NULL
pointer. Instead, it also returns the constant NULL.
Interview question #9
What are the differences between malloc() and calloc()?
malloc() calloc()
malloc() accepts one argument of type calloc() accepts two arguments of type
size_t with the following prototype: size_t with the following prototype:
malloc() can allocate one block of memory. calloc() can allocate multiple blocks of
memory.
malloc() does not clear the allocated calloc() clears the allocated memory. i.e.,
memory. it places zeros in allocated bytes.
malloc() function allocates memory as calloc() function expects the total
chained link. expected memory to be continuous.
The function realloc() adjusts the amount of memory allocated to the block to size, copying the contents
to a new location if necessary.
Arguments: block is the pointer to the memory block that is previously obtained by calling malloc(),
calloc() or realloc(). If block is NULL pointer, realloc() works just like malloc().
Size is the new size for allocated block.
Return value:
On success, this function returns the address of the reallocated block, which might be different
from the address of the original block.
On failure, i.e., if the block can’t be reallocated or if the size passed is 0, the function returns NULL.
The function realloc() is more useful when the maximum size of allocated block can not be decided in
advance.
Ex: int *a;
a=(int *) malloc(30); //first 30 bytes of memory is allocated.
a=(int *) realloc(a,15); //later the allocated memory is shrink to 15 bytes.
Interview question #10
Why does not sizeof operator tell us the size of block of memory pointed by a pointer?
The sizeof operator does not know the at malloc() has been used to allocate pointer; sizeof tells
us the size of the pointer itself. There is no portable way to find out the size of a block allocated
by malloc().
Program #14
Write a program to access a 2-D array using pointer and print it in matrix form
#include<stdio.h>
main()
{
int a[10][10],m,n,i,j;
int (*ptr)[10]; //pointer-to-array
printf(“\n Enter the matrix row and column values:”);
scanf(“%d%d”,&m,&n);
Output:
printf(“\n Enter matrix elements:”);
Enter matrix row and column values: 2 2
for(i=0;i<m;i++)
Enter matrix elements: 23 45 65 232
for(j=0;j<n;j++)
The matrix elements:
scanf(“%d”,&a[i][j]);
23 45
ptr=a;
65 232
printf(“\n The matrix elements:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,*(*(ptr+i)+j));
printf(“\n”);
}
}
b=(int **)malloc(p*sizeof(int));
for(i=0;i<m;i++)
a[i]=(int *)malloc(q*sizeof(int));
printf("\n Enter second matrix elements");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
printf(“\n Second matrix\n”);
display(b,p,q);
multiply(a,b,m,n,p,q);
free(a);
free(b);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf(“\n The resultant matrix:\n”);
display(c,m,q);
free(c);
}
for(i=0;i<m;i++)
a[i]=(int *)malloc(n*sizeof(int));
Output:
Given string is= Ravi Chandra
The length of string=12
3. Once a string has been defined using character array, it can’t be initialized to another set of
characters. Unlike character array, such an operation is perfectly valid with char pointer.
Ex: #include<stdio.h>
main()
{
char message[]=”Bye Forever”;
char *p=”Bye forever”;
message=”welcome friend”; // A blunder
p=”Welcome friend”;
}
for(i=0;i<n;i++)
names[i]=(char *) malloc(15*sizeof(char));
for(i=0;i<n;i++)
{ for(j=i+1;j<n;j++)
{ if(strcmp(names[i],names[j])>0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
printf(“\n Names in alphabetical order:”);
for(i=0;i<n;i++)
printf(“%s\t”,names[i]);
}
Output:
Enter how many strings: 5
Enter 5 names:
Master
Minister
Servant
King
Queen
Names in alphabetical order: King Master Minister Queen Servant
A pointer is a special type of variable that holds address as a data item in it. The address is may be
of a variable, or of a constant, or of an array, or of a function, or of another pointer.
A pointer can hold the base address of an array that is collection of elements.
A pointer can be assigned to another pointer (of same type only) directly.
2) q is a constant pointer.
q will never be changed. But *q will be changed.
From this function definition, it is clear that the function main() takes these two arguments:
argc- an integer argument that holds the total number of arguments that are supplied at command
prompt.
argv- a pointer to a character array or pointer-to-pointer-to character that holds all the strings (or
arguments) supplied at command prompt.
Program #23
}
Output:
$cc sumnum.c
$./a.out 12 43 65 34 //suggestion: (separate each string with space)
sum=154
11.17. Conclusion
A pointer is a special type of variable that holds address as a data item in it. The address is may be of a
variable, or of a constant, or of an array, or of a function, or of another pointer. Pointers play key role in
allocating memory as and when it is needed. In order to return more than one value to a calling function,
the concept of pointers is more helpful. It is very much needed in construction of complex data structures
like linked lists, trees and graphs. If we use pointers properly, it is very much helpful in diverse
applications. Its improper use causes the system to be hanged.