Session-14
Session Overview
Pointers and Arrays
Pointers and Strings
Array of Pointers
Array of Pointers to Strings
Pointers and Functions
Multiple Indirection
Dynamic Memory Allocation
1
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Arrays
An Array name is actually a Pointer to the first element in that Array.
Therefore, if ‘ary’ is a single-dimensional Array, the address of the first Array
element can be expressed as either &ary[0] or simply as ary.
Similarly, the address of the second Array element can be written as &ary[1] or
as ary+1, and so on.
In general, the address of the (i+1)th Array element can be expressed as either
&ary[i] or as (ary+i).
Thus, the address of an Array element can be expressed in two ways:
By writing the actual Array element preceded by the ampersand sign (&)
By writing an expression in which the subscript is added to the Array name.
2
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Arrays contd.
Remember that in the expression (ary+i), ary represents as address, whereas i
represents as integer quantity.
Moreover, ary is the name of an Array whose elements can be either integers,
characters, floating point, and so on.
Therefore, the above expression is not a mere addition; it is actually specifying
as address, which is a certain number of memory cells beyond the first.
The expression (ary+i) is in true sense, a symbolic representation for an address
specification rather than arithmetic expression.
The number of memory cells associated with an Array element will depend on
the data type of the Array as well as the computer’s Architecture.
3
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Arrays contd.
However, the user can specify only the address of the first Array element, that
is the name of the Array and the number of Array elements beyond the first,
that is, a value for the subscript.
The value of i is sometimes referred to as an offset when used in this manner.
The expression &arry[i] and (ary+i) both represent the address of the ith
element of ary, and so it is logical that *(ary+i) both represent the contents of
that address, that is the value of the ith element of ary.
Both terms are interchangeable can be used in any particular application as
desired by the programmer.
4
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Arrays contd.
Single-dimensional main( )
{
10 element integer Array
int ary[10]={1,2,3,4,5,6,7,8,9,10};
Values are displayed in int i;
two ways for(i=0;i<10;i++)
{
ary[i], *(ary+i) printf(“\ni=%d ary[i]=%d *(ary+i)=%d”, i, ary[i], *(ary+i));
Addresses are displayed in printf(“&ary[i]=%X ary+i=%X , &ary[i], ary+i);
two ways }
}
&ary[i], ary+i
i=0 ary[i]=1 *(ary+i)=1 &ary[i]=194 ary+i=194
i=1 ary[i]=2 *(ary+i)=2 &ary[i]=196 ary+i=196
i=2 ary[i]=3 *(ary+i)=3 &ary[i]=198 ary+i=198
..... ….. ….. ….. ….
i=9 ary[i]=10 *(ary+i)=10 &ary[i]=1A6 ary+i=1A6
5
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Arrays contd.
When assigning a value to an array element such as ary[i], the left side of the
assignment statement can be written as either ary[i] or as *(ary+i).
Thus, a value may be assigned directly to an Array element or it may be
assigned to the memory area whose address is that of the array element.
The address of one element cannot be assigned to some other element, though
the value of one Array element can be assigned to another through Pointers.
&ary[2] = &ary[3]; /* not allowed */
ary[2] = ary[3]; /* allowed*/
6
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Multidimensional Arrays
As a single dimensional Array can be represented in terms of a Pointer (the
Array name) and an offset (the subscript).
So, also a multidimensional Array can be represented with an equivalent
Pointer notation.
This is because a multidimensional Array is actually a collection of single
dimensional Arrays.
For example, a two-dimensional Array can be defined as a Pointer to a group of
contiguous one-dimensional Arrays.
A two-dimensional Array declaration can be written as:
data_type (*ptr_var) [expr 2]; instead ofdata_type array [expr 1] [expr 2];
7
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Multidimensional Arrays
In these declarations data_type refers to the data type of the Array, ptr_var is
the name of the pointer variable, exp1 is a positive valued integer expressions
that indicate the maximum number of Array elements.
Note the parentheses that surround the Array name and the preceding asterisk
in the pointer version of each declaration.
These parentheses must be present; else the definition would represent an
Array of pointers rather than a pointer to a group of Arrays.
For example, if ary is a two dimensional array having 10 rows and 20 columns, it
can be declared as
int (*ary) [20]; instead of int ary [10] [20];
8
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Multidimensional Arrays
int (*ary) [20]; 20 Columns
ary
ary + 2 will point
to this row
*(*(ary+3) + 8);
instead of
ary [3][8];
ary[3][8] int ary [10] [20];
same as *(ary[3]+8)
same as *(*(ary+3)+8)
9
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 14
Pointers Pointers and Strings
Strings are nothing but single dimensional character Arrays.
Arrays and Pointers are closely related.
Suppose we wish to store “Hello”. char str[]=“Hello”
We may either store it in a String (or) char *p=“Hello”
We may ask the C compiler to store it at some location in memory and assign the
address of the String in a char pointer.
main( )
There is a difference in usage of two forms. {
char str1[]=“Hello”;
char str2[];
For example, we cannot assign a String to another,
char *s=“Good Morning”;
whereas, we can assign a char pointer to another char *q;
str2=str1; /* error */
char pointer. q=s; /* valid */
}
10
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 14
Pointers Pointers and Strings contd.
Once a String has been defined it cannot be initialized main( )
{
to another set characters. char str1[]=“Hello”;
char *p=“Hello”;
Unlike Strings, such an operation is perfectly valid with str1=“Bye”; /* error */
char pointers P=“Bye”; /* valid */
}
In another case, Consider the case of the function strchr( )
This function takes as arguments a String and a character to be searched for in that
String.
ptr_str = strchr(str1,’a’);
Therefore in the Pointer variable ptr_str will be
assigned the address of the first occurrence of the character ‘a’ in the String str.
This is not the position in the String, from 0 to the end of the String but the address,
from where the String starts to the end of the String.
11
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Strings example
A pointer variable ptr is set main( )
{
to hold address returned by char a, str[80], *ptr, *strchr();
strchr() printf(“\n Enter a Sentence”);
gets(str);
Program prints the printf(“\n Enter Character to search for: ”);
a=getche();
address of start of the String, ptr=strchr(str,a);
the address of the character, printf(“\n Position of first occurrence (starting from 0)”);
printf(“is: %d”, ptr - str);
the character’s position
}
relative to the start of String
Enter a Sentence: We are learning Pointers
Enter character to search for: P
Position of first occurrence (starting from 0) is: 16
The relative position is the difference between the two addresses, the address of the start
of the String and the address where the character’s first occurrence is found.
12
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Array of Pointers
The way there can be an Array of ints or an Array of floats, similarly there can
be an Array of Pointers.
Since a Pointer variable always contains an address, an Array of Pointers would
be 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.
int *ptr_ary[10]; The declaration creates an Array named ptr_ary containing
10 elements, each of which is of the type int *.
13
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Array of Pointers contd.
main( )
{
char *arr[4]; /* Array of integer Pointers */
int i=31,j=5,k=19,l=71,m; i j k l
arr[0] = &i; 31 46 5 83
arr[1] = &j; 6500 6502 6504 6506
arr[2] = &k;
arr[3] = &l;
arr[0] arr[0] arr[2] arr[3]
for(m=0;m<=3;m++) 6500 6502 6504 6506
{ 6508 6510 6512 6514
printf(“%d”,*(arr[m]));
}
}
14
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Array of Pointers contd.
A multi-dimensional Array can be expressed in terms of an Array of Pointers
rather than as a Pointer to a group of contiguous Arrays.
In general, a two dimensional Array can be defined as a one-dimensional Array
of Pointers as:
data_type *ary[exp 1]; data_type ary[exp 1] [exp 2];
rather than
The Array name and its preceding asterisk are not enclosed in Parentheses in
this type of declaration.
A right to left rule first associates the pairs of square brackets with ary, defining
the named object (ary) as an Array.
The preceding asterisk then establishes that the Array will contain Pointers.
Remember that, the last(rightmost) expression is omitted when defining an
Array of Pointers, whereas the first (leftmost) expression is omitted when
defining a pointer to a group of Arrays. 15
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 14
Pointers Array of Pointers contd.
In an Array expressed in this manner, an individual Array element within the n-
dimensional Array can be accessed by a single use of the indirection operator, *
Consider a two-dimensional Array ary having 10 rows and 20 columns. In this
case, ary can be defined as a single-dimensional Array by writing :
Here ary[0] points to the beginning of the first row, ary[1] points to the
beginning of the second row, and so on.
In this kind of definition, the number of elements in each row is not specified
explicitly.
int *ary[10];
An individual Array element, such as ary[3][8] can be accessed by:
*(ary[3]+8); which refers toary[3][8];
16
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Array of Pointers to Strings
Pointer Arrays provide a convenient method for storing Strings.
As Strings are character Arrays, each Array element (of the Pointer Array) is a
character-type Pointer that indicates the beginning of a separate String.
Thus, an n-element Array can point to n different Strings.
Referring to its corresponding pointer each String can be accessed.
Suppose that the following Strings are to be stored in a Character-type Array:
Dennis , Ritchie, Computer, Programming
These Strings can be stored in a two-dimensional, character type Array as
char name[4][14];
17
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Array of Pointers to Strings
Note that name contains 10 rows, to accommodate the 4 Strings.
Each row must be large enough to store at least 10 Characters, as well as the
null character (\0) at the end.
To provide for larger Strings, each String is defined to have at least 14
characters.
A better way to do this is to define a 4-element of Pointers, that is,
char *name[4]; D e n n i s
name[1] R i t c h i e
C o m p u t e r
name[3] P r o g r a m m i n g
18
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Array of Pointers to Strings
main( )
{
char *names[ ]= Dennis\0 Ritchie\0 Computer\0 Programming\0
{ 6500 6507 6515 6524
“Dennis”,
“Ritchie”, names[] 35 needed
“Computer”, Instead of 44
6500 6507 6515 6524
“Programming”
6608 6610 6612 6614
};
}
Efficient use of available memory
names[] is an Array of Pointers. It contains base addresses of respective names.
Base address of “Dennis” is stored in names[0], and so on.
Thus after the end of each String, a null character is inserted, and from next
memory location next String follows.
19
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Pointers and Functions
main( )
Using Call by Reference intelligently we
can make a function return more than {
one value at a time, which is not int radius;
possibly ordinarily. float area, perimeter;
printf(“\n Enter a radius of a circle”);
We have been able to indirectly return scanf(“%d”,&radius);
two values from a called function, and areaperi(radius, &area, &perimeter);
hence, have overcome the limitation printf(“\n Area =%f”, area);
of the return statement. printf(“\n Perimeter =%f”, perimeter);
}
areaperi(int r, float *a, float *p)
Output: {
Enter radius of a circle : 5 *a=3.14 * r *r;
Area = 78.500000 *p=2 * 3.14 *r;
Perimeter = 31.400000 }
20
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 14
Pointers Multiple Indirection
It is possible to have a Pointer to another Pointer that points to the target value.
This is called Multiple indirection or Pointers to Pointers.
In this case, the value of the normal Pointer is the address of the variable that
contains the desired value.
In case of a Pointer to a Pointer, the first Pointer contains the address of the
second Pointer, which points to the variable that contains the desired value.
Excessive indirection is difficult to follow and prone to conceptual errors.
A variable that is a Pointer to a Pointer must be declared. Placing an additional
asterisk in front of the variable name does this.
21
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Multiple Indirection
For example, the following declaration tells the compiler that fl_ptr is a Pointer to
a Pointer type float. float **fl_ptr;
fl_ptr is not a Pointer to a floating point number but rather a Pointer to a float
Pointer.
To access the target value indirectly pointed to by a Pointer to a Pointer, the
asterisk operator has to be applied twice.
main( )
{
int x, *ptr, **p_ptr; p_ptr ptr X
x=10; 1005 1010 10
ptr=&x; 1000 1005 1010
p_ptr=&ptr;
printf(“%d”, **p_ptr);
22
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Session 14
Pointers Dynamic Memory Allocation
An Array name is actually a Pointer to the first element of the Array.
It is possible to define the Array as a Pointer variable rather than the
conventional Array.
However, if an Array is declared conventionally, it results in a fixed block of
memory being reserved at the beginning of the program execution.
Where this does not occur if the Array is represented as a Pointer variable.
As a result the use of Pointer variable to represent an Array requires some sort of
initial memory assignment before the Array elements are processed.
Such memory allocations are generally done using the malloc() library function.
23
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Dynamic Memory Allocation contd.
Consider an example, A single-dimensional integer array ary having 20 elements
can be defined as int *ary; instead of int ary[20];
However, ary will not be automatically assigned a memory block when it is
defined as a Pointer variable, though a block of memory enough to store 10
integer quantities will be reserved in advance if ary is defined as an Array.
Either value has to be assigned to each element of ary at the time of initialization
or memory has to be assigned to it.
ary = (int *) malloc(20*sizeof(int));
If ary is defined as a Pointer, sufficient memory can be assigned as shown above.
malloc() returns a Pointer of type Void. However, since ary is a Pointer to type int,
type casting is necessary. In the above statement (int *) casts malloc so as to
return a Pointer to type int.
24
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Dynamic Memory Allocation contd.
This will reserve a block of memory whose size (in bytes) is equivalent to the size
of integer Array, ary.
Here a block of memory for 20 integers is allocated. The number 20 is multiplied
by the return value of the function sizeof(int).
As we know that 2 bytes are required to store an integer, the computer reserves
40 bytes of memory for the Array ary.
The function malloc() returns a Pointer which is the address location of the
starting point of the memory allocated.
If enogh memory space does not exist, malloc() returns NULL value.
The allocation of memory in this manner, that is as and when required in a
program is known as Dynamic Memory Allocation.
25
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Dynamic Memory Allocation contd.
A C program can store information in the Main memory in 2two primary ways.
Global and Local variables (storage is fixed, programmer knows the amount of
memory needed for every situation in advance.)
Dynamic Memory Allocation System (storage of information is allocated from the pool
of free memory as and when needed)
On contrast with malloc(), free() function releases the memory pointed to by the
Pointer, and make memory available for further allocation.
Remember that free() can only be called with a Pointer that was previously
allocated with the Dynamic allocation system’s functions.
Using an invalid pointer in the call to free() will probably destroy the memory
management and cause a system crash.
26
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]
Session 14
Pointers Dynamic Memory Allocation example
#include <stdio.h> Contd..
#include<malloc.h> for(i=0;i<2;i++)
#include<conio.h> {
main() clrscr();
{ printf("\nMarks for Student %d are \n\n", i+1);
int i,j, (*stud_mk)[10]; for(j=0;j<3;j++)
stud_mk = (int *) malloc(2*3*sizeof(int)); {
for(i=0;i<2;i++) printf("\n%d Subject %d ",j+1,
{ *(*stud_mk+i)+j);
printf("\n Enter marks for Student %d\n", i+1); }
for(j=0;j<3;j++) getch();
{ }
printf("\n%d Subject ",j+1); free(stud_mk);
scanf("%d", *(stud_mk+i)+j); }
}
getch(); 3 marks for 2 students are read,
} Memory is allocated using malloc( ) function
27
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P
[email protected] Next Session
Fighting with Files
Thank You
28
26 Jul 2013 Prepared by: Lakshmi Rajeswara Rao.P [email protected]