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

Lesson11 Pointers

Uploaded by

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

Lesson11 Pointers

Uploaded by

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

Pointers 11

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

11.2. Advantages of pointers


Pointers are used frequently in C, as they offer a number of benefits to the programmers. These include:
 Pointers can be used to access and manipulate data stored in memory directly.
 Pointers allow C to support dynamic memory allocation.
 Pointers provide an efficient way to create and manipulate efficient data structures such as stacks,
queues, linked lists, trees and graphs.
 Pointers increase the execution speed and thus reduce the program’s execution time.
 Pointers are more efficient in handling arrays and data tables.
 The use of pointer arrays to strings results in saving of data storage space in memory.
 Pointers allow to change the calling function’s arguments and to return multiple values from called
function.
 Pointers permit references to functions and thereby facilitating passing of functions as arguments
to other functions.
The real power of C lies in the proper use of pointers. The misuse of pointers causes serious problems
such as system crash.
Department of CSE 2 Pointers
11.3. Referencing operator (&)
Referencing operator is a unary operator. It acts on one operand at a time. It returns the address of
operand. The operand must be a named region of storage (like int variable, array variable, pointer
variable etc.) for which a value may be assigned. The operand must not be a constant or an expression or
a register variable. This operator is also called as “address of” operator.

The & operator should be preceded with the operand in order to return the address.

&Operand_1

Valid expressions: &a //where a is the name of variable.


&c //where c is the name of an array.
&fact //where fact is the name of function.
Invalid expressions: &253 //constant can’t be used as an operand.
&(a+b) //expression can’t be used as an operand.
&r //register type can’t be used as an operand.

Consider the declaration:


int a=20;
This declaration tells the C compiler to:
a) Reserve the required space in memory to hold the integer value.
b) Associate the name a with this memory location.
c) Store the value 20 at this location.
Suppose that the variable a occupies 2 bytes on 16-bit computer. This can be represented as follows:

a Name of variable

20 Value of variable (data item)

Address of variable (byte0 address)


1000

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).

Department of CSE 3 Pointers


Program #1
Write a program to print the address of variable in hexa decimal and decimal notations
#include<stdio.h>
main()
{
int a=20;
printf(“\n The address of a =%x”,&a); //prints address in hexa decimal notation
printf(“\n The address of a=%u”,&a); // prints the address as a positive long integer
printf(“\n The address of a=%p”,&a);
}
Output:

Interview question #2
What are the differences between referencing operator and bitwise AND?

Referencing operator (&) Bitwise AND (&)


It is a unary operator. It acts on one It is a binary operator. It acts on two
operand at a time. operands at a time.
The operand is the name of variable, array, The operands are groups of bits.
pointer, function or structure.
It returns the address of byte0 of the It returns the result of bitwise AND
operand. operation on bits.

11.4. Dereferencing operator (*)


Dereferencing operator is a unary operator. It acts on one operand at a time. It returns the value stored
at the address of operand. The operand must be an address, a pointer that holds address or a pointer
expression. This operator is also called as “value at address” operator or indirection operator.
The * operator should be preceded with the operand in order to return the value at address of operand.

*Operand_1

Valid expressions: *(&num) //where num is a variable


*&*&num
**&num

Invalid expressions: *2009 //constant value can’t be used as an operand.


*num //only addresses or pointers or pointer expressions can be used.
(*&)num //parentheses should not enclose two unary operators

Department of CSE 4 Pointers


Program #2
Write a program to print the content of a variable
#include<stdio.h>
main()
{
int a=20;
printf(“\n The value of a=%d”,a);
printf(“\n The value of a=%d”,*(&a));
}
Output: The value of a=20
The value of a=20

Interview question #3
What are the differences between Indirection operator and Arithmetic operator?

Indirection operator (*) Arithmetic operator(*)


It is a unary operator. It acts on one It is a binary operator. It acts on two
operand at a time. operands at a time.
The operand is the address of a variable or The operands are two variables or
a pointer or a pointer expression. expressions those return numeric values.
It returns the value at the address of the It returns the product of two operands.
operand.

11.5. Working with pointers


In order to work with pointers, do the following:
1. Declare a pointer variable
2. Initialize it.
3. Access the original value through a pointer or perform any other operation on it.

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:

<storage_class> <data type> * <Pointer_name(s)>;

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

Department of CSE 5 Pointers


The declaration int *iptr; does not mean that iptr is going to contain integer value. What it means is,
iptr is a pointer variable that is going to hold the address of an integer value. Hence, iptr is a pointer that
points to integer value. In short, iptr is a pointer-to-int.
In the same way, the pointer fptr is going to contain the address of floating point value. Hence,
fptr is a pointer that points to a floating point value. In short, fptr is a pointer-to-float.
Similarly, the pointer cptr is going to contain the address of a character. Hence, cptr is a pointer
that points to a character. In short, cptr is a 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.

Ex: int a=40;


int *iptr1,*iptr2; //Declaring pointer variables: iptr1,iptr2
iptr1=&a; //Initializing pointer variable: iptr1
iptr2=iptr1; //Initializing pointer variable: iptr2
Whenever a pointer variable is initialized with the address of an ordinary variable or a pointer variable, we
can say that the pointer variable points to that ordinary variable or pointer variable. This can be
represented as follows:

9879 7654 3245


Points to Points to
7654 40 7654

iptr1 a iptr2

Interview question #4

What is a void pointer (generic pointer)?


A void pointer is a pointer to which any other type of pointer or address of any other type of variable,
array, function or structure can be assigned. It can be declared as follows:
Ex: void *vptr; //generic pointer: pointer-to-void
int a=10,*iptr=&a; vptr=iptr; //vptr holds pointer-to-int
float b=13.53,*fptr=&b; vptr=fptr; //vptr holds pointer-to-float

Department of CSE 6 Pointers


Point to ponder#3

Since a generic pointer has no object type, it can not be de-referenced.

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).

Accessing a pointer variable:


Once a pointer variable is initialized, it can be used to access the address as well as content of object to
which it is pointed to. The following program demonstrates this:

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

printf(“\n The address of a=%u”,&a);


printf(“\n The address of a=%u”,iptr); //accessed to print address of a

printf(“\n The value of a=%d”,a);


printf(“\n The value of a=%d”,*(&a));
printf(“\n The value of a=%d”,*iptr); //accessed to print the content of a
}
Output: The address of a=
The address of a=
The value of a=40
The value of a=40
The value of a=40

Department of CSE 7 Pointers


Interview question #6
Define pointer-to-pointer?
If a pointer variable is initialized with the address of another pointer variable, then we can say that
pointer is a pointer-to-pointer.

11.6. Operations on pointers


11.6.1. Pointer arithmetic
The following arithmetic operations can be performed on pointers:
 Addition of a number to a pointer.
 Subtraction of a number from a pointer.
 Subtraction of a pointer from another pointer.

The following arithmetic operations can not be performed on pointers:


× Addition, multiplication, division and modulo division of two pointers.
× Multiplication, division and modulo division of a pointer by a number.
× Shifting operations.

Department of CSE 8 Pointers


Pointer increment and decrement:

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.

11.6.2. Pointer comparisons


Two pointers can be compared by using relational operators as well as logical operators. When these
operators encountered, these expressions may return either true or false. The following program
demonstrates this:

Department of CSE 9 Pointers


Program #4
Write a program to demonstrate pointer comparisons
#include<stdio.h>
main()
{
int a=40,b=34;
int *iptr1,*iptr2;
iptr1=&a;
iptr2=&b;
printf(“\n Equal condition of two pointers=%d”,(ip1==ip2));
printf(“\n Not Equal condition of two pointers=%d”,(ip1!=ip2));
printf(“\n Greater than condition of two pointers=%d”,(ip1>ip2));
printf(“\n Lesser than condition of two pointers=%d”,(ip1<ip2));
printf(“\n Greater than or equals condition of two pointers=%d”,(ip1>=ip2));
printf(“\n Lesser than or equals condition of two pointers=%d”,(ip1<=ip2));
printf(“\n Logical AND condition of two pointers=%d”,( ip1>=ip2&&ip1==ip2));
printf(“\n Logical OR condition of two pointers=%d”,(ip1==ip2|| ip1<ip2));
printf(“\n Logical NOT condition of two pointers=%d”,(!(ip1==ip2)));
}
Output:

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.

11.7. Pointers and functions


11.7.1. Pointer as an argument
Pointers can also be passed as arguments to a function as normal values are being passed. This method is
also known as call by reference. By using these pointers, the calling function’s arguments can be changed
from called function. Whenever we want to pass a pointer as an argument, these things should be carried
out:
 In function prototype, place an * after the type of argument to specify that we are passing a
pointer as an argument.
 In function call, place the argument- the address of operator followed by name of argument or the
pointer that is declared earlier.
 Develop the function definition based on the specified prototype.

The following program demonstrates these:

Department of CSE 10 Pointers


Program #5
Write a program to increment three values from called function and print them in calling
function.
#include<stdio.h>
void increment(int *,int *,int *); //function prototype
main()
{
int a=20,b=30,c=40;
printf(“\n Before increment a=%d\tb=%d\tc=%d”,a,b,c);
increment(&a,&b,&c); //function call
printf(“\n After increment a=%d\tb=%d\tc=%d”,a,b,c);
}
void increment(int *x,int *y,int *z) //function definition
{
++*x;
++*y;
++*z;
}
Output:

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:

Department of CSE 11 Pointers


11.7.2. Pointer as a return value
Pointers can also be returned to the calling function from called function as normal values. When we want
to return a pointer to the calling function from called function, we should do these:
 In function prototype, place an ‘*’ after the return type to indicate that the function returns a
pointer.
 In calling function, there should be a pointer variable that is declared to hold the pointer that is
returned. However, both types should be the same to avoid ambiguities.
 Develop the function definition as specified in function prototype. In function definition, the return
statement, at end, should consist of an ‘&’ before the return value or a pointer that is declared
earlier.
Point to ponder #4
Returning a pointer to local argument of called function to calling function gives you a warning.

The following program demonstrates these:


Program #7
Write a program that demonstrates pointer as return value
#include<stdio.h>
int * add(int,int); //function prototype—function add() returns a pointer-to-int
main()
{
int a,b;
int *c;
printf(“\n Enter the values of a and b: ”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“\n The result=%d”,*c);
}
int * add(int x,int y) //function definition
{
int z;
z=x+y;
return (&z);
}

Output:
Enter the values of a and b: 10
12
The result=22

Department of CSE 12 Pointers


11.7.3. Pointer-to-function
We can also call a function using a pointer. To call a function using a pointer, do the following:
1. First, declare a pointer to function that has the following form:

<return type> (*<name_of_ptr)(arg_type_1,arg_type_2,…);

E.g., int (*addptr)(int,int);


The above declaration tells that addptr is a pointer to a function that takes two integer
arguments and returns an integer value.
2. Assign the name of the function to that pointer. The name of the function itself acts as an address
of function.
E.g., addptr=add; // add should be the name of function
3. Call the function by using pointer in the same way as we call a function.
E.g., x=(*addptr)(10,20);
The above statement is used to call that function which is already assigned to pointer-to-function.

The following program demonstrates a pointer-to-function:


Program #8
Write a program that demonstrates pointer-to-function
#include<stdio.h>
int add(int,int); //function prototype – No change, give prototype normally.
main()
{
int a,b,c;
int (*addptr)(int,int); //step-1: pointer-to-function declaration
printf(“\n Enter the values of a and b: ”);
scanf(“%d%d”,&a,&b);
addptr=add; //step-2: Assign name of function to the pointer
c=(*addptr)(a,b); //step-3 call the function using pointer
printf(“\n The result=%d”,c);
}
int add(int x,int y) //function definition- No change, give definition normally
{
int z;
z=x+y;
return z;
}

Output:
Enter the values of a and b: 10
12
The result=22

Department of CSE 13 Pointers


11.7.4. Passing a function as an argument to another function
A pointer-to-function can be passed to another function as an argument. This allows one function to be
transferred to another function. Let us refer to the first function as the guest function and the second
function as host function. Thus the guest function is passed to the host function, where it can be
accessed. When we want to pass a function as an argument to another function, do the following:

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

Department of CSE 14 Pointers


11.8. Casting pointers
A pointer always has a type associated with it. As we can convert a variable of one type to another, we
can also convert one type of pointer to another type of pointer. This process of conversion is called as
casting pointers. Unlike variables, we can’t assign one type of pointer variable with another type of pointer
variable, although both of them have memory addresses as their values. This is known as incompatibility
of pointers.
We can’t use the assignment operator with the pointers of different types. We can, however, make
explicit assignment between two incompatible pointer types by using cast operator, as we do with
fundamental types. The cast operator can be used as follows:

<ptr1>=(<data type> *)<ptr2>;

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

Department of CSE 15 Pointers


11.9. Dynamic memory allocation
Though arrays can be used for data storage, they are of fixed size. The programmer must know the size of
the array while writing the program. In most situations, it is not possible to know the size of the memory
required until run time. At execution time, a program can request more memory from a free memory pool
(heap). Dynamic memory allocation refers to the allocation of such memory during program execution.
The only way to access this dynamically allocated memory is through pointers.
Interview question #7
What are the differences between dynamic memory allocation and static memory
allocation?

Static memory allocation Dynamic memory allocation


It is the process of allocating memory at It is the process of allocating memory
compile time. during execution of program.
Fixed number of bytes will be allocated. Memory is allocated as and when it is
needed.
The memory is allocated in memory stack. The memory is allocated from free
memory pool (heap).

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().

1) malloc() — allocates a block of memory


The function malloc() has the following prototype:

void *malloc(size_t size);


The function malloc() allocates a block of size bytes from the free memory pool (heap). It allows a
program to allocate an exact amount of memory explicitly, as and when needed.
Argument: The parameter passed to malloc() is of the type size_t. This type is declared in the header file
stddef.h. size_t is equivalent to the unsigned int data type. Thus, in compilers where an int is 16 bits in
size, malloc() can allocate a maximum of 64KB at a time, since the maximum value of an unsigned int is
65535.
Return value:
 On success, i.e., if free memory is available, malloc() returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type before
using it to access the memory allocate.
 On failure, i.e., if enough free memory does not exist for block, malloc() returns NULL. The
constant NULL is defined in stdio.h to have a value zero. Hence, it is safe to check the return value.

Department of CSE 16 Pointers


Ex: 1) malloc(30); allocates 30 bytes of memory and returns the address of byte0.
2) malloc(sizeof(float)); allocates 4 bytes of memory and returns the address of byte0.
Interview question #8
What do malloc(-20) and malloc(0) return?
The parameter to malloc() function should be an unsigned integer. If we pass any negative value as an
argument, then NULL is returned. So, malloc(-20) returns NULL.

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.

2) calloc() — allocates multiple blocks of memory


The function malloc() has the following prototype:

void *calloc(size_t nitems,size_t size);


calloc() provides access to the C memory heap, which is available for dynamic allocation of variable-sized
blocks of memory.
Arguments: Unlike malloc(), the function calloc() accepts two arguments: nitems and size. The parameter
nitems specifies the number of items to allocate and size specifies the size of each item.
Return value:
 On success, i.e., if free memory is available, calloc() returns a pointer to the newly allocated
memory. Usually, it is generic pointer. Hence, it should be typecast to appropriate data type before
using it to access the memory allocated.
 On failure, i.e., if enough free memory does not exist for block, calloc() returns NULL. The constant
NULL is defined in stdio.h to have a value zero. Hence, it is safe to verify the return value before
using it.
Ex: 1) calloc(3,5); allocates 15 bytes of memory and returns the address of byte0.
2) malloc(6,sizeof(float)); allocates 24 bytes of memory and returns the address of byte0.

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:

void *malloc(size_t size); void *calloc(size_t nitems,size_t size);

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.

Department of CSE 17 Pointers


3) realloc() — grows or shrinks allocated memory
The function malloc() has the following prototype:

void *realloc(void *block,size_t size);

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().

4) free() — de-allocates memory


The function free() has the following prototype:

void free(void *block);


The function free() de-allocates a memory block pointed by block.
Argument: block is the pointer that is points to allocated memory by malloc(), calloc() or realloc(). Passing
an uninitialized pointer, or a pointer to a variable not allocated by malloc(), calloc() or realloc() could be
dangerous and disastrous.
Ex: int *a;
a=(int *) malloc(30); //first 30 bytes of memory is allocated.
free(a); //de-allocates 30 bytes of memory.
Interview question #11
How does free() know how many bytes to free?
The malloc() / free() implementation remembers the size of each block allocated and returned.
So, it is not necessary to remind it of the size when freeing.

Department of CSE 18 Pointers


11.10. Pointers and One-Dimensional numeric arrays
An array is homogeneous collection of elements stored in contiguous memory locations referred by
common name. The array name itself is the base address, i.e., the address of first element in array. As we
know that the pointer is an address, the array name itself is a pointer.
11.10.1. Accessing array elements through a pointer
Usually, each element in an array is accessed through an index that starts from 0 and ends with n-1
where n is the size of array. e.g., a[0] is the first element, a[1] is second element and so on…
Similarly, by using a pointer variable, all the elements are accessed as follows:
1. First declare a pointer variable. The type of pointer variable should be same as the type of array.
2. Initialize the pointer variable with the base address of array.
3. Access each element by placing an * before incremented pointer or before the expression of the
form (ptr+i) where ptr is the pointer variable and i is the index value.
The following program demonstrates this:
Program #11
Write a program to add elements of array using a pointer.
#include<stdio.h>
void display(int *,int);
void sum(int *,int);
main()
{
int a[10],n,i,*ptr; //step-1: Declaration of a pointer variable
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
printf(“\nEnter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
ptr=&a[0]; //step-2: Initalization of pointer variable
display(a,n); //the name of the array itself is the base address
sum(ptr,n);
}
void display(int a[],int n)
{
int i; Note: a[i] is equivalent to
printf(“\n The array elements are:”); i[a] or *(a+i) or *(i+a)
for(i=0;i<n;i++)
printf(“%d\t”,a[i]);
}
void sum(int *ptr,int n)
{
int i,total;
total=0;
//step-3: Accessing array elements through pointer
for(i=0;i<n;i++)
total=total+*ptr++; //or total=total+*(ptr+i);
printf(“\n The sum of array elements=%d”,total);
}
Output:
Enter the array size:5
Enter the array elements: 2 4 6 3 1
The array elements are: 2 4 6 3 1
The sum of array
Department of CSE elements=16 19 Pointers
11.10.2. Dynamically allocated 1-D array
When we declare an array, we declare it as an array of fixed size. It can’t be grown or shrink as and when
needed. To overcome this problem, dynamically allocated array is introduced. To work with dynamically
allocated array, do the following:
1. Declare a pointer variable.
2. Allocate memory to that pointer variable.
3. Initialize and access array elements through pointer variable.
4. De-allocate the pointer variable.
The following program demonstrates this concept:
Program #12
Write a program to sort elements of array using pointers.
#include<stdio.h>
void display(int *,int);
void sort(int *,int);
main()
{
int *a,n,i; //step-1: Declaration of a pointer variable
printf(“\n Enter the array size:”);
scanf(“%d”,&n);
a=(int *) malloc(n*sizeof(int)); //step2: Allocate memory
printf(“\nEnter the array elements:”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
display(a,n);
sort(a,n);
free(a); //step-4: de-allocating memory
}
void display(int a[],int n)
{ Note: a[i] is equivalent to
int i; i[a] or *(a+i) or *(i+a)
printf(“\n The array elements are:”);
for(i=0;i<n;i++)
printf(“%d\t”,a[i]); //step-3: accessing elements
}
void sort(int *ptr,int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n-i-1;j++)
{
if(*(ptr+i)>*(ptr+j)) //step-3: accessing elements
{
temp=*(ptr+i);
*(ptr+i)=*(ptr+j);
*(ptr+j)=temp;
}
}
}
printf(“\n After sorting:”);
display(ptr,n);
}

Department of CSE 20 Pointers


Interview question #12
Can we use the content of allocated memory after freeing it?
Some early documentation for malloc() stated that the contents of freed memory were “left
undisturbed”. So, few programmers would use the contents of freed memory deliberately.

11.10.3. Function returning 1-D array


By using pointers, a function can return more than one value at a time. As array contains more than one
element and array name is the base address, we can return the base address. This gives us a view that a
function can return more than one value at a time. The following program demonstrates this concept:
Program #13
Write a program to demonstrate a function that returns a sorted array.
#include<stdio.h>
int * sort(int a[],int); //function prototype
main()
{
int *p;
int a[10],n,i;
printf("\n Enter the array size:");
scanf("%d",&n);
printf("\n Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Before sorting:");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
p=sort(a,n); //function call- p holds the base address of returned array
printf("\n After sorting:");
for(i=0;i<n;i++)
printf("%d\t",*p++);
}
int *sort(int a[],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return a; //sends the base address of sorted array
}
Output:
Enter the array size: 5
Enter the array elements:35
3
46
43
1
Before sorting: 35 3 46 43 1
After sorting:
Department of CSE1 3 35 43 46 21 Pointers
11.11. Pointers and Two-Dimensional numeric arrays
The two-dimensional array is an array with two subscripts. As same with one-dimensional numeric array,
the name of two-dimensional array is also a base address. i.e., it is the address of element that is present
in first row and first column (address of a[0][0]).
11.11.1. pointer-to-2-D array
The way we can have a pointer to an integer, or a pointer to a float, can we also have a pointer to an
array? The answer is YES. A two-dimensional array can be accessed through a pointer as follows:
1. First, declare a pointer to array. This declaration of pointer-to- 2-D array is little clumsy. It has the
following form:

<data type> (*<ptr_name>)[size];

Ex: int (*q)[4];


This declaration gives a meaning that q is a pointer-to-2-D array of 4 columns.
2. Once a pointer is declared, it should be initialized with the name of 2-D array that was declared
and initialized earlier.
e.g., ptr=a; where a is two-dimensional array.
3. Now, each element gets accessed with the help of the following expression:
*(*(ptr+i)+j) where i is the index of row and j is the index of column.

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”);
}
}

Department of CSE 22 Pointers


11.11.2. Dynamically allocated 2-D array
When we declare an array, we declare it as an array of fixed size. It can’t be grown or shrink as and when
needed. To overcome this problem, dynamically allocated array is introduced. To work with dynamically
allocated array, do the following:
1. Declare a pointer variable.
2. Allocate memory to that pointer variable.
3. Initialize and access array elements through pointer variable.
4. De-allocate the pointer variable.
The following program demonstrates this concept:
Program #15
/*A program to multiply two matrices using pointers*/
#include<stdio.h>
void display(int **,int,int);
void multiply(int **,int **,int,int,int,int);
main()
{
int **a,**b,m,n,p,q,i,j; //step-1

printf("\n Enter the first matrix order:");


scanf("%d%d",&m,&n);
printf(“\n Enter second matrix order:”);
scanf(“%d%d”,&p,&q);
if(n!=p)
printf(“\n Sorry, matrix multiplication is not possible”);
else
{
a=(int **)malloc(m*sizeof(int));
for(i=0;i<m;i++) step-2
a[i]=(int *)malloc(n*sizeof(int));
printf("\n Enter first matrix elements");
for(i=0;i<m;i++)
for(j=0;j<n;j++) step-3
scanf("%d",&a[i][j]);
printf(“\n First matrix\n”);
display(a,m,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);
}
}

Department of CSE 23 Pointers


void display(int **a,int m,int n)
{
nt i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf(“\n”);
}
}
void multiply(int **a,int **b,int m,int n,int p,int q)
{
int **c,i,j;
c=(int **)malloc(m*sizeof(int));
for(i=0;i<m;i++)
c[i]=(int *)malloc(q*sizeof(int));

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);
}

11.11.3. Array of pointers


There is an array of ints or an array of floats. Similarly, there can also be an array of pointers. Since, a
pointer is an address; an array of pointers is nothing but a collection of addresses. The addresses present
in the array of pointers can be addresses of isolated variables or addresses of array elements or any other
addresses. All rules that apply to an ordinary array apply to the array of pointers as well. The following
program demonstrates the concept of array of pointers:
Program #16
Write a program to demonstrate array of pointers.
#include<stdio.h>
main()
{
int *a[4]; //declaration of array of pointers
int i=32,j=45,k=2,l=35,m;
a[0]=&i;
a[1]=&j;
a[2]=&k;
a[3]=&l;
for(m=0;m<3;m++)
printf(“%d\t”,*(a[m])); //accessing the content in each element that is a pointer
}
Output: 32 45 2 35

Department of CSE 24 Pointers


Program #17
Write a program to print transpose a matrix using array of pointers.
#include<stdio.h>
main()
{
int *a[10];
int m,n,i,j;

printf("\n Enter matrix order");


scanf("%d%d",&m,&n);

for(i=0;i<m;i++)
a[i]=(int *)malloc(n*sizeof(int));

printf("\n Enter matrix elements:");


for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

printf("\n The original matrix\n");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[j][i]);
printf("\n");
}

printf("\n The transpose of matrix\n");


for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf("%d\t",a[j][i]);
printf("\n");
}
}
Output:
Enter matrix order: 2 3
Enter matrix elements: 1 2 3 4 5 6
The original matrix
1 2 3
4 5 6
The transpose of matrix
1 4
2 5
3 6

Department of CSE 25 Pointers


Program #18
Write a program to print transpose of a matrix using pointer-to-array
#include<stdio.h>
main() Output:
{ Enter matrix row and column values: 2 2
int a[10][10],m,n,i,j; Enter matrix elements: 23 45 65 232
int (*ptr)[10]; //pointer-to-array The matrix elements:
printf(“\n Enter the matrix row and column values:”); 24 45
scanf(“%d%d”,&m,&n); 65 232
printf(“\n Enter matrix elements:”); The transpose of matrix:
for(i=0;i<m;i++) 24 65
for(j=0;j<n;j++) 45 232
scanf(“%d”,&a[i][j]);
ptr=a;
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”);
}
}
printf(“\n The transpose of matrix:\n”);
for(i=0;i<n;i++)
{ for(j=0;j<m;j++)
{
printf(“%d\t”,*(*(ptr+j)+i));
printf(“\n”);
}
}
}

Interview question #13


Compare array of pointers to pointer-to-array?
1) A pointer to an array is a variable that contains the address of (points to) a multi-dimension variable
that could contain anything (multiple strings or multiple longs etc.).
An array of pointers is a single-dimensional variable that holds muliple addresses (pointers) each of
which could point to anything (other variables, objects etc.).

2) The number in subscript of pointer-to-array denotes the number of columns.


The number in subscript of array of pointers denotes the number of rows.

Department of CSE 26 Pointers


11.12. Pointers and Strings
As a group of integers is stored in an integer array, a group of characters will be stored in a character
array. This character array is called as a string. Usually, a string constant is a one-dimensional array of
characters terminated by a null character (\0).
11.12.1. Accessing a string by using a pointer
Because a string is one-dimensional array of characters and the array name is the base address, the name
of the character array also becomes the base address. In order to access string with the help of pointer,
do the following:
1. First declare a pointer of type char.
e.g., char *ptr; //A character pointer
2. Initialize the pointer with the name of character array that was declared and initialized earlier.
e.g., char s[]=”Ravi Chandra”;
ptr=s; //holds the base address of character array ‘s’
3. Access each character of string with the help of pointer by incrementing once till the \0 character is
encountered.
e.g., while(*ptr!=’\0’)
{
printf(“%c”,*ptr);
ptr++;
}
Program #19
Write a program to read a string and print a string along with its length
#include<stdio.h>
int stringlength(char *);
main()
{
char s[]=”Ravi Chandra”;
char *ptr;
int len;
cptr=s;
len=stringlength(s);
printf(“\n The length of string=%d”,len);
}
int stringlength(char *s)
{
int count=0;
printf(“\n Given string is=”);
while(*s!=’\0’)
{
printf(“%c”,*s);
count++;
s++;
}
return count;
}

Output:
Given string is= Ravi Chandra
The length of string=12

Department of CSE 27 Pointers


Program #20
Write a program to count number of alphabets, digits, spaces and special characters in a line
of text
#include<stdio.h>
main()
{
char line[100];
char *ptr;
int nalpha,ndigit,nspace,nspecial;
printf(“\n Enter a line of text:”);
scanf(“%[ ^\n]”,line);
ptr=line;
nalpha=nspace=ndigit=nspecial=0;
while(*ptr!=’\0’)
{
if(toupper(*ptr)>=’A’ && toupper(*ptr)<=’Z’)
nalpha++;
else if(*ptr>=’0’&&*ptr<=’z’)
ndigit++;
else if(*ptr= =’ ‘ || *ptr= =’\t’)
nspace++;
else
nspecial++;
}
printf(“\n No.of alphabets=%d”,nalpha);
printf(“\n No.of digits=%d”,ndigits);
printf(“\n No.of spaces=%d”,nspace);
printf(“\n No.of special characters=%d”,nspecial);
}
Output:
Enter a line of text: Master says, “B.Tech 1st year students are brilliant”
No.of alphabets=41
No.of digits=1
No.of spaces=5
No.of special symbols=4

11.12.2. Pointer to a string


Suppose we wish to store the string “Hello friend”. We may either store it in a character array or we may
ask the C compiler to store it some where in memory and assign the address of that string in a char
pointer. This is shown below:
char message[]=”Hello friend”;
char *p=”Hello friend”;
However, there are differences between these two:
1. The size of character array will be more than the size of the character pointer.
Ex: #include<stdio.h>
main()
{
char message[]=”Hello friend”;
char *p=”Hello friend”;
printf(“\n Size of character array=%d”,sizeof(message));
printf(“\n Size of character pointer=%d”,sizeof(p));
}

Department of CSE 28 Pointers


Output (on 32-bit machine):
Size of character array=13
Size of character pointer=4
2. A char pointer can be assigned to another char pointer; but a character array can’t be assigned to
another character array.
Ex: #include<stdio.h>
main()
{
char message[]=”Hello friend”;
char mesg2[20];
char *p=”Hello friend”;
char *q;

mesg2=message; //A blunder


q=p; //works
}

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”;
}

11.12.3. Array of pointers to strings


As an array of integer pointers is used to represent a two-dimensional array of integers, array of character
pointers is used to hold multiple strings. To deal with multiple strings with the help of array of character
pointers, do the following:
1. First, declare an array of character pointers.
e.g., char *a[10];
This declaration is used to define a 10-element array of pointers. Thus, a[0] points to first
string, a[1] points to second string and so on.
2. It is not necessary to include a maximum string size within declaration. However, it is necessary to
allocate maximum string size as follows:
for(i=0;i<n;i++) // n is number of strings
a[i]=(char *) malloc(15*sizeof(char)); //15 is each string’s maximum length
3. After memory is allocated, the array of character pointers can be initialized and accessed as normal
arrays.

The following program demonstrates this concept:

Department of CSE 29 Pointers


Program #21
Write a program to sort names using array of character pointers.
#include<stdio.h>
main()
{
int n,i,j;
char *names[10],*temp;

printf(“\n Enter how many strings:”);


scanf(“%d”,&n);

for(i=0;i<n;i++)
names[i]=(char *) malloc(15*sizeof(char));

printf(“\n Enter %d names:”,n);


for(i=0;i<n;i++)
scanf(“%s”,names[i]);

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

Interview question #14


Why can’t I get strcat() to work? I tried
char *s1=”Hello”;
char *s2=”World”;
strcat(s1,s2);
printf(“%s”,s1);
The main problem here is that the space for the concatenated result is not properly allocated. C
compilers allocate memory only for specified objects explicitly mentioned in the source code. The
programmer must arrange for sufficient space for the results of run-time operations, such as string
concatenation, typically by declaring arrays or by calling malloc().
The strcat() function performs no allocation. Since, there is no space for concatenated result in
first string (or destination string), the strcat() function returns run-time error.

Department of CSE 30 Pointers


Interview question #15
Compare arrays and pointers?
1) An array is a homogeneous collection of elements stored in contiguous memory locations referred
by a common name.

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.

2) An array can hold a collection of pointers.

A pointer can hold the base address of an array that is collection of elements.

3) An array can’t be assigned to another array (even of same type) directly.

A pointer can be assigned to another pointer (of same type only) directly.

4) A pointer can be incremented.

An array name (though it is an address of first element) can not be incremented.

5) The size of array is fixed. It can never be changed.

The memory allotted to a pointer can be reallocated.

Department of CSE 31 Pointers


11.13. Pointers and const
As we know that const is the keyword that is used to define a symbolic constant that never be changed
throughout the program. E.g., the following is the constant definition:
const float PI=3.1412;
This definition defines a constant PI and this value never be changed through out the program.
11.13.1. Pointer to constant
When we want to deal with a pointer to constant, do the following:
1) Declare a pointer to constant that has the following form:

const <data type> * <ptr_name>;

E.g., const int *p;


The above statement declares p as a pointer to constant integer.
2) Once a pointer is declared, initialize it with the address of a const value or const array.
E.g., const int a=23;
p=a; //initialization of pointer with base address of array of constants
3) Access the const value or const array with the help of pointer.
It is important to note that the value that is being pointed can never be changed. But the pointer that
points to constant can be changed. In other words, it can be incremented or decremented.
E.g., The following program demonstrates this concept:
#include<stdio.h>
main()
{
const int *ptr1,*ptr2;
const int i=20;
const int a[]={10,20,40,23};
ptr1=&i;
ptr2=a;
printf(“%d”,*ptr1); //prints the value of i
i=30; //a blunder—trying to change the content of const
printf(“%d”,*ptr1);
ptr2++; //valid—a pointer to const can be changed
printf(“%d”,*ptr2); // prints the value of a[1]
}
Note: These types of pointers are very useful in char pointers, when pointers are to be passed to a
function for printing. Suppose, we are writing a function that is aimed to print a character string, it is good
practice to code that function as follows:
void printstring(const char *str)
{
printf(“%s”,str);
}
The above function accepts a pointer of type const char *(pointer to constant character). The string that
is being pointed can never be changed. This is safety measure, since it prevents the accidental
modification of the string that is being passed to called function.
Points to ponder #6
Pointer-to-constant means that the value is not changed through that pointer, not which is unchanged
Department of CSE through any
32 pointer. Pointers
11.13.2. Constant pointer
When we want to deal with a constant pointer, do the following:
1) Declare a constant pointer that has the following form:

<data type> * const <ptr_name>=<address>;

E.g., int a=20;


int * const p=&a;
The above statement declares p as a constant pointer that holds the address of a.
2) Access the constant pointer to print the original content of variable or array whose address is stored.
E.g., printf(“%d”,*p); //prints the value of a
It is important to note that the value that is being pointed can be changed. In the above example, the
value of a can be changed. But the value of constant pointer can never be changed. i.e., in the above
example, p++ or ++p is invalid.
Note: const int * const p=&a;
The above declaration disallows the modification of both p and a. i.e., both pointee and pointer.
Interview question #15
What is the difference between const char *p and char* const q?
1) p is a pointer-to-constant char.
P will be changed. But *p will never be changed.

2) q is a constant pointer.
q will never be changed. But *q will be changed.

11.14. Command line arguments


We can also pass arguments to the function main() as we pass arguments to other functions. The main()
function accepts two arguments: argc (argument count) and argv (argument vector). It has the following
form:
main(int argc,char *argv[])
{
}
(or)
main(int argc,char **argv)
{
}

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.

Department of CSE 33 Pointers


When we want to write a program that deals with command line arguments, do the following:
1. First, write the program with the above definition.
2. Compile it successfully.
3. While running it, supply more arguments along with ./a.out. Because we are supplying the
arguments at command prompt ($ in unix), these arguments are called as command line
arguments.
Program #22

Write a program to demonstrate command line arguments


#include<stdio.h>
main(int argc,char *argv[])
{
printf(“\n Number of arguments supplied=%d”,argc);
if(argc!=3)
{
printf(“\n Insufficient number of arguments”);
exit(0);
}
printf(“\n The arguments supplied are:”);
for(i=0;i<argc;i++)
printf(“\t%s”,argv[i]);
}
Output:
$cc command.c
$./a.out apple boy cat dog //suggestion: (separate each string with space)
Number of arguments supplied=5 //(including a.out)
The arguments supplied are: a.out apple boy cat dog

Program #23

Write a program to add numbers using command line arguments


#include<stdio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
int sum,i;
for(i=1,sum=0;i<argc;i++)
sum=sum+atoi(argv[i]); //atoi() function converts a string to number
printf(“\n sum=%d”,sum);

}
Output:
$cc sumnum.c
$./a.out 12 43 65 34 //suggestion: (separate each string with space)
sum=154

Department of CSE 34 Pointers


11.15. Various pointer declarations
Declare a variable of type float?
float x;
Declare an array that holds 10 floating-point values?
float a[10];
Declare a function that takes a character as argument and returns a character as return value?
char fun(char);
Declare a pointer-to-float?
float *fptr;
Declare a function that returns a pointer-to-float?
float * fun(void);
Declare a pointer-to-function that takes a double argument and returns a double value?
double (*fun)(double);
Declare a pointer-to-10-integer element array?
int (*arrptr)[10];
Declare an array of integer pointers of size 10?
int *a[10];
Declare a pointer to char?
char *cptr;
Declare a pointer-to-pointer to a char?
char **cptr;
Declare a pointer-to-pointer-to-pointer to a char?
char ***cptr;
Declare a function that returns a pointer to the array of floats?
float (*fun())[10];
Declare an array of pointers to a function returning float?
float (*f[10])();

11.16. Problems with pointers


1) Segmentation fault (or segfault):
This generally means that a program tried to access the memory it shouldn’t have, invariably as a result
of improper pointer use. The most likely causes could be inadvertent use of null pointers or uninitialized,
misaligned, or otherwise improperly allocated pointers, corruption of malloc area and mismatched function
arguments, especially involving pointers; two possible cases are scanf(“%d”,i) (without ampersand) and
fprintf(invalid FILE* argument).
A segmentation fault occurs when an attempt is made to access memory whose address is well-
formed, but to which access can’t be granted. This might be due to either a protection fault or an invalid
page fault.
2) Un-initialized pointer:
This generally occurs when we declared a pointer, forgot to initialize it with an address and tried to access
the content through pointer. E.g.,
int *ptr, val=300;
*ptr=val; /*Error*/
3) When we want to assign a value to a pointer variable, then that assignment leads to an
error. E.g., int *p, val=24;
p=val; /*Error*/
4) When we want to assign the address of un-initialized variable to a pointer, then that
assignment also leads to an error.

Department of CSE 35 Pointers


E.g., int val,*ptr;
ptr=&val; /*Error*/
5) When we want to compare pointers those point to different objects, that comparison lead to
an error
E.g., char name1[20],name2[20];
char *p1=name1;
char *p2=name2;
if(p1>p2)…. /*Error*/

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.

Department of CSE 36 Pointers

You might also like