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

Unit 6

Uploaded by

Dr D Suneetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit 6

Uploaded by

Dr D Suneetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter-6: POINTERS:

Aims and Objectives


###################

Introduction to pointers
C provides the important feature of data manipulations with the address of the variables, the
execution time is very much reduced such concept is possible with the special data type called
Pointers.
A pointer is a variable that represents the location (rather than the value) of a data item, such
as a variable of an array.
Pointers can be used to pass information back and forth between a function and its reference
point. In particular, pointers provide a way to return multiple data items from a function via
function arguments.
Pointers are also closely associated with arrays and therefore provide an alternative way to
access individual array elements.
The computer memory is a sequential collection of storage cells.
This statement instructs the system to find a location for the integer variable ‘a’ and puts the
value 50 in that location. Let us assume that the system has chosen the address location 2000 for
a.
printf(“a=%d address=%u\n”a, &a);
output:
a=50 address=2000

Declaration:
datatype *ptname;
This tells the compiler three things about the variable ptname.
1. The * tells that the variable ptname is a pointer variable.
2. ptname needs a memory location.
3. ptname points to a variable of type datatype.
Ex:
int *p;
Declares the variable p as a pointer variable, that points to an integer data type. Remember that
the type int refers to the datatype of the variable being pointed to by p and not the type of the
pointer.
Similarly
float *x;
declares x as a pointer to a floating point variable.
Once a pointer variable has been declared, it can be made to point to a variable using an assignment
statement such as
P = &a;
which causes p to point to a.
i.e., p now contains the address of ‘a’. This is known as pointer initialization. Before a pointer is
initialized, it should not be used.
Pointer: A pointer is a variable which stores the address of another variable. Declaration:- Pointer
declaration is similar to normal variable declaration but preceded by a *
Syntax:- data type *identifier;
Example:- int *p;
Initialization:- datatype *identifier=address;
Example:- int n;
int *p=&n;
NULL:-NULL pointer value(empty address)
Any type of pointer allocates two bytes of memory because it stores address of
memory allocation.In c language the programme keep ([memory]) size is 64 kilo bytes.It is in
unsigned integer range.
NOTE:- Any type of pointer it allocates 2 bytes memory. Because it stores address of memory
location.
Program:
#include<stdio.h>
#include<conio.h> void
main()
{
int *p1; char
*p2; float
*p3; double
*p4; clrscr();
printf("\n Size of int pointer:%d bytes", sizeof(p1)); //size of(*) printf("\n
Size of char pointer:%d bytes", sizeof(p2)); //size of(*) printf("\n Size of
float pointer:%d bytes", sizeof(p3)); //size of(*) printf("\n Size of double
pointer:%d bytes", sizeof(p4)); //size of(*) getch();
}

Concept of Pointers
####################
Declaring Pointer Variables: ##############
Assigning Pointers: ################
Initialization of a Pointer: #############
Accessing a Pointer’s Contents: ############

Use of Pointers
####################
Drawbacks (or) Disadvantages of Pointers
############################
Relationship between Pointers and Arrays
############################
Memory Usage in Pointers,
################################
FUNCTIONS AND POINTERS
Call by Reference:- The process of calling a function using pointers to pass the address of the
variables is known as call by reference.
Expand the data
#######################
Program: #include<stdio.h>
#include<conio.h>
void main()
{
void disp(int *);
int n;
clrscr();
disp(&n);
printf("%5d",n); getch();
}
void disp( int *x)
{
printf("Enter any value into n:"); scanf("%d",x);
}
Program: Swapping two values
#include<stdio.h> #include<conio.h>
void main()
{
void swap(int *, int *);
int a,b;
clrscr();
printf("Enter any two values:");
scanf("%d%d",&a,&b); printf("\
nBefore swaping:"); printf("\na=
%d",a);
printf("\nb=%d",b);
swap(&a,&b); printf("\nAfter
swaping:"); printf("\na=
%d",a);
printf("\nb=%d",b);
getch();
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Dangling Memory/Dangling Pointers
Dangling pointers arise when an object is deleted or de-allocated, without modifying the value of
the pointer, so that the pointer still points to the memory location of the de-allocated memory. The
pointer still points to the same location in memory even though the reference has since been
deleted and may now be used for other purposes.
A straightforward example is shown below:
{
char *dp = NULL;
/* ... */
{
char c; dp = &c;
} /* c falls out of scope */
/* dp is now a dangling pointer */
}
If the operating system is able to detect run-time references to null pointers, a solution to the above is
to assign 0 (null) to dp immediately before the inner block is exited. Another solution would be to somehow
guarantee dp is not used again without further initialization.
Another frequent source of dangling pointers is a jumbled combination of malloc() and free() library
calls: a pointer becomes dangling when the block of memory it points to is freed. As with the previous
example one way to avoid this is to make sure to reset the pointer to null after freeing its reference—as
demonstrated below.
#include <stdlib.h>
void func()
{
char *dp = malloc(A_CONST);
/* ... */
free(dp); /* dp now becomes a dangling pointer */ dp
= NULL; /* dp is no longer dangling */
/* ... */
}
Pointer arithmetic
Pointer arithmetic actually move the pointer reference by an arithmetic operation. i.e addition and
subtraction.
For example:
int x = 5, *ip;
ip = &x;
ip++;

From the above mentioned code, ip is an integer pointer that points address of integer variable x.

ip++ represents an increment operation performed on a pointer variable. it will increment by 2


bytes (since size of int is 2) and points to the next memory location.

Pointer arithmetic is very useful when dealing with arrays. Consider the following example:
#include <stdio.h>
void main ()
{
int array[] = { 45, 67, 89 }; int
* array_ptr;
array_ptr = array;
printf(" first element: %i\n", *(array_ptr++));
printf("second element: %i\n", *(array_ptr++));
printf(" third element: %i\n", *array_ptr); getch();
}

OUTPUT
first element: 45
second element: 67
third element: 89

Similarly, decrement operation will move the pointer to previous memory cell.
ip= ip+n is equivalent to ip= ip+ n * sizeof(data type(ip)) ip= ip-n is
equivalent to ip= ip - n * sizeof(data type(ip))
However, following operations are invalid upon pointers Invalid
pointer arithmetic include:
(i) Adding, dividing and multiplying two pointers
(ii) Adding double or float to pointer
(iii) Masking or shifting pointer
(iv) Assigning a pointer of one type to another type of pointer.

Character Pointers and Functions


A string constant, written as
"I am a string"
is an array of characters. In the internal representation, the array is terminated with the null
character ’\0’ so that programs can find the end. The length in storage is thus one more than the
number of characters between the double quotes.
Perhaps the most common occurrence of string constants is as arguments to functions, as in
printf("hello, world\n");
When a character string like this appears in a program, access to it is through a character
pointer; printf receives a pointer to the beginning of the character array. That is, a string
constant is accessed by a pointer to its first element.
String constants need not be function arguments. If pmessage is declared as
char *pmessage;
pmessage = "now is the time";
assigns to pmessage a pointer to the character array. This is not a string copy; only pointers are
involved. C does not provide any operators for processing an entire string of characters as a unit.
There is an important difference between these definitions:
char amessage[] = "now is the time"; /* an array */ char
*pmessage = "now is the time"; /* a pointer */
amessage is an array, just big enough to hold the sequence of characters and ’\0’ that initializes it.
Individual characters within the array may be changed but amessage will always refer to the same
storage. On the other hand, pmessage is a pointer, initialized to point to a string constant; the
pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to
modify the string contents.
/* strcpy: copy t to s; pointer version 2 */ void
strcpy(char *s, char *t)
{
while ((*s++ = *t++) != ’\0’)
;
}
This moves the increment of s and t into the test part of the loop. The value of *t++ is the
character that t pointed to before t was incremented; the postfix ++ doesn’t change t until after this
character has been fetched. In the same way, the character is stored into the old s position before
s is incremented. This character is also the value that is compared against ’\0’ to control the loop.
The net effect is that characters are copied from t to s, up and including the terminating ’\0’.

Relevance of data type in pointer variable


##############################

Pointer Arithmetic and Arrays


############
Pointers to Pointers
############
Pointers to void
############
Null Pointers
############
Pointers for inter function communication
############

POINTERS AND ARRAYS


When an array is declared, the compiler allocates a BASE address and sufficient amount of storage
and contain all the elements of array in continuous memory allocation. The base address is the
location of the first element (index 0 of the array).The compiler also defines the array name as a
constant pointer pointed to the first element.
suppose we declare an array 'a' as follows.
Example:- int a[5]={1,2,3,4,5};
Suppose the base address of a is 1000 and assuming that each integer requires 2 bytes. Then the 5
elements will be stored as follows.
Elements------> a[0] a[1] a[2] a[3] a[4]
------------------------------
values-------> 1 2 3 4 5
-----------------------------
address------> 1000 1002 1004 1006 1008

base address

Here 'a' is a pointer that points to the first element. so the value of a is 1000 there fore
a=&a[0]=1000
If we declare 'p' is an integer pointer, then we can make the pointer p to point to
the array 'a' by the following assignment.
int *p;
p=&a[0]=a;
Now we can access every value of a using p++(or)p+1 to move one element to another. The
relationship between p and a is shown below.
p+0 = &a[0]=1000
p+1 = &a[1]=1002
p+2 = &a[2]=1004
p+3 = &a[3]=1006
p+4 = &a[4]=1008
When handling arrays instead of using array indexing, we can use pointer to access array
elements. Note that *(p+k) gives the value of a[k]. Pointer accessing method is much faster than
array indexing.

Program:
#include<stdio.h>
#include<conio.h> void
main()
{
int n[5];
int *p=n;
clrscr();
printf("n[0]=%u",&n[0]); printf("\nn=%u",n);
printf("\nn[0]=%u",p); getch();
}
Program: Write a program to accept and display array elements using pointers
#include<stdio.h>
#include<conio.h> void
main()
{
int a[20],n,i;
int *p=&a[0];
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:"); for(i=0;i<n;i++)
{
scanf("%5d",p+i);
}
printf("Given array elements:"); for(i=0;i<n;i+
+)
{
printf("%5d",*(p+i));
}
getch();
}

Difference between Array Name and Pointer


######################
POINTERS & 2D ARRAYS
Each row of a two-dimensional array can be thought of as a one-dimensional array. This is a very
important fact if we wish to access array elements of a two-dimensional array using pointers.
Suppose we want to refer to the element s[2][1] using pointers. We know that s[2] would give
the address 65516, the address of the second one-dimensional array. Obviously (65516 + 1) would
give the address 65518. Or (s[2]+1) would give the address 65518. And the value at this address can be
obtained by using the value at address operator, saying *(s[2]+1). But, we have already studied while
learning one-dimensional arrays that num[i] is same as*(num+i). Similarly,*(s[2] + 1) is same as,
*(*(s+2)+1). Thus, all the following expressions refer to the same element,
s[2][1]
* (s [2] + 1 )
* (* (s + 2) + 1)

As an example,
&a[1][2] = *(a+1)+2
a[1][2] = *(*(a+1)+2)
Therefore, & a[i][j] is equivalent to *(a+i)+j
a[i][j] is equivalent to *(*(a+i)+j)
/* Pointer notation to access 2-D array elements */ main( )
{

int s[4][2] = { { 1234, 56 }, { 1212, 33 }, { 1434, 80 }, { 1312, 78 } } ;


int i, j ;
for ( i = 0 ; i <4 ; i++ )
{
printf ( "\n" ) ;
for ( j = 0 ; j < 2 ; j++ )
printf ( "%d ", *( *( s + i ) + j ) ) ;
}

}
And here is the output...
1234 56

1212 33

Department of BS&H Page 130


NRI Institute of Technology, Pothavarappadu
1434 80
1312 78

/*pointer notation to read and write a 2d array */ main()


{
int a[3][3],i,j;
printf(“Enter a 3X3 Matrix\n”);
for(i=0 ; i<3 ; i++)
for(j=0 ; j<3; j++)
scanf(“%d”, *(a+i)+j);
printf(“Displaying elements of 3X3 Matrix\n”);
for(i=0 ; i<3 ; i++)
for(j=0 ; j<3 ; j++) printf(“%d”,
*(*(a+i)+j));
}

Pointer arithmetic
###################

DYNAMIC MEMORY ALLOCATION


C language requires the no of elements in an array to be specified at compile time.But
we may not be able to do so always our initial judgement of size,if it is wrong,it make cause
failure of the program (or) wastage of the memory space.In this situation we use Dynamic
Memory allocation.
Definition:-The process of allocating memory at run time is known as Dynamic memory
allocation.

Malloc():- <alloc.h>
It is a function which is used to allocating memory at run time.
Syntax:- void *malloc(size_t size);
size_t:- unsigned integer. this is used for memory object sizes.

Pointer variable=(type casting)malloc(memory size);


Example:- int *p;
p=(int *)malloc(sizeof(int)); //for 1 location p=(int
*)malloc(n*sizeof(int)); //for n locations

Calloc():- <alloc.h>
This is also used for allocating memory at run time.
Syntax: void *calloc(size_t nitems, size_t size);

NOTE:- Calloc allocates a block (n times*size)bytes and clears into 0.

Difference between malloc and calloc:


1. Malloc defaultly store garbage value where as calloc defaultly stores zero
2. In malloc only one argurment we will pass where as in calloc we will pass two

Department of BS&H Page 131


NRI Institute of Technology, Pothavarappadu
arguments
Expand the data
#################
Program:Write a program to create a dynamic array (vector) store values from keyboard display
#include<stdio.h>
#include<conio.h>
#include<malloc.h> void
main()
{
int *a,n,i;

Department of BS&H Page 132


NRI Institute of Technology, Pothavarappadu
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
a=(int *)malloc(n* sizeof(int));
//a=(int *)calloc(n,sizeof(int)); printf("Enter
array elements:"); for(i=0;i<n;i++)
{
scanf("%d",a+i);
}
printf("Given array elements:"); for(i=0;i<n;i+
+)
{
printf("%d\t",*(a+i));
}
getch();
}
Program: Write a program to create a dynamic memory allocation for two dimensional array and
read values from keyboard and display
#include<stdio.h>
#include<conio.h>
#include<malloc.h> void
main()
{
int **a,r,c,i,j;
clrscr();
printf("Enter no of rows and columns:");
scanf("%d%d",&r,&c);
a=(int **)malloc(r* sizeof(int *));
//a=(int *)calloc(n,sizeof(int));
for(i=0;i<r;i++)
{
*(a+i)=(int *)malloc(c*sizeof(int));
}
printf("enter array elements:\n"); for(i=0;i<r;i+
+)
{
for(j=0;j<c;j++)
{
scanf("%d",*(a+i)+j);
}
}
printf("Given array elements:"); for(i=0;i<r;i+
+)
{

Department of BS&H Page 133


NRI Institute of Technology, Pothavarappadu
for(j=0;j<c;j++)
{
printf("%3d\t",*(*(a+i)+j));
}
printf("\n");
}
free(a);
getch();
}

Program:Write a program to create a variable to column size array in read values


#include<stdio.h>
#include<conio.h>
#include<malloc.h> void
main()
{
int **a,r,*c,i,j; clrscr();
printf("Enter no of rows:");
scanf("%d",&r);
c=(int *)malloc(r* sizeof(int));
//a=(int *)calloc(n,sizeof(int));
for(i=0;i<r;i++)
{
printf("enter no of cols for row %d:",i+1);
scanf("%d",c+i);
}
a=(int **)malloc(r* sizeof(int *)); for(i=0;i<r;i++)
{
*(a+i)=(int *)malloc(*(c+i)*sizeof(int));
}
printf("enter array elements:\n"); for(i=0;i<r;i+
+)
{
for(j=0;j<*(c+i);j++)
{
scanf("%d",*(a+i)+j);
}
}
printf("Given array elements:\n\n");
for(i=0;i<r;i++)
{
for(j=0;j<*(c+i);j++)
{

Department of BS&H Page 134


NRI Institute of Technology, Pothavarappadu
printf("%3d\t",*(*(a+i)+j));
}
printf("\n");
}
free(a);
getch();
}

Command-line arguments
The C language provides a method to pass parameters to the main() function. This is typically
accomplished by specifying arguments on the operating system command line (console).
The prototype for main() looks like: int
main(int argc, char *argv[])
{

}
There are two parameters passed to main(). The first parameter is the number of items on the
command line (int argc). Each argument on the command line is separated by one or more spaces,
and the operating system places each argument directly into its own null- terminated string. The
second parameter passed to main() is an array of pointers to the character strings containing each
argument (char *argv[]).
For example, at the command prompt:
test_prog 1 apple orange 4096.0
There are 5 items on the command line, so the operating system will set argc=5 . The parameter argv is
a pointer to an array of pointers to strings of characters, such that:
argv[0] is a pointer to the string “test_prog” argv[1]
is a pointer to the string “1”
argv[2] is a pointer to the string “apple” argv[3]
is a pointer to the string “orange” argv[4] is a
pointer to the string “4096.0”

Department of BS&H Page 135


NRI Institute of Technology, Pothavarappadu
Example program for Command line arguments

1. #include <stdio.h>
2.
3. int main(int argc, char *argv[]) { if
4. ( argc != 3) {
5. printf("Usage:\n %s Integer1 Integer2\n",argv[0]);
6. }
7. else {
8. printf("%s + %s = %d\n",argv[1],argv[2], atoi(argv[1])+atoi(argv[2]));
9. }
10. return 0;
11 }
.
Explanation
line 4 : we check if the user passed two arguments to the program. We actually need two
arguments but in C the first argument ( argv[0] ) is the name of our program, so we need two
more.
line 5 : If the user didn't pass two arguments we print the usage of our program and exit line 8 :
Using atoi() function we convert pointers to char (string) to decimal numbers and display their
sum.
C program prints the number and all arguments which are passed to it.
#include <stdio.h>
void main(int argc, char *argv[])
{
int c;
printf("Number of command line arguments passed: %d\n", argc);

for ( c = 0 ; c < argc ; c++)


printf("%d. Command line argument passed is %s\n", c+1,argv[c]);

}
/*program to find large and small from an array using a function*/
#include<stdio.h> find(x,m,l,s)
int x[];
int m; int
*l,*s;
{
int i;
*l=*s=x[0];
for(i=1;i<m;i++)
{
if (x[i]>*l)
*l=x[i];
if (x[i]<*s)
*s=x[i];

Department of BS&H Page 136


NRI Institute of Technology, Pothavarappadu
}
}

main()
{
int a[10],n,i,lar,sma;
clrscr();
printf("enter n"); scanf("%d",&n);
printf("enter array elements\n"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
find(a,n,&lar,&sma);
printf("largest=%d smallest=%d\n",lar,sma); getch();
}

Pointer and Functions (passing pointers to functions, returning pointers fom functions).
######################

POINTER TO A POINTER

As the definition of pointer says that its a special variable that can store the address of an other
variable. Then the other variable can very well be a pointer. This means that its perfectly legal for
a pointer to be pointing to another pointer.
Lets suppose we have a pointer ‘p1′ that points to yet another pointer ‘p2′ that points to a character ‘ch’.
In memory, the three variables can be visualized as :

So we can see that in memory, pointer p1 holds the address of pointer p2. Pointer p2 holds the
address of character ‘ch’.
So ‘p2′ is pointer to character ‘ch’, while ‘p1′ is pointer to ‘p2′ or we can also say that ‘p2′ is a
pointer to pointer to character ‘ch’.
Now, in code ‘p2′ can be declared as :
char *p2 = &ch;
But ‘p1′ is declared as :
char **p1 = &p2;
So we see that ‘p1′ is a double pointer (ie pointer to a pointer to a character) and hence the two
*s in declaration.

Department of BS&H Page 137


NRI Institute of Technology, Pothavarappadu
Now,
 ‘p1′ is the address of ‘p2′ ie 5000
 ‘*p1′ is the value held by ‘p2′ ie 8000
 ‘**p1′ is the value at 8000 ie ‘c’
example :
#include<stdio.h>

int main(void)
{
char **ptr = NULL;

char *p = NULL;

char c = 'd';

p = &c;
ptr = &p;

printf("\n c = [%c]\n",c);
printf("\n *p = [%c]\n",*p); printf("\
n **ptr = [%c]\n",**ptr);

return 0;
}

Pointers and Strings


Suppose we wish to store “Varma”. We may either store it in a string or 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. This is
shown below:
char str[ ] = "Varma" ; char
*p = "Varma" ;
There is a difference in usage of these two forms. For example, we cannot assign a string to
another, whereas, we can assign a char pointer to another char pointer. This is shown in the
following program.
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ; char
*q ;
str2 = str1 ; /* error */ q
= s ; /* works */
}
Also, once a string has been defined it cannot be initialized to another set of characters. Unlike
strings, such an operation is perfectly valid with char pointers.

Department of BS&H Page 138


NRI Institute of Technology, Pothavarappadu
main( )
{
char str1[ ] = "Hello" ; char
*p = "Hello" ;
str1 = "Bye" ; /* error */ p
= "Bye" ; /* works */
}

Array of Pointers
##################
Pointer to Array
##################
Various Alternatives of Accessing Arrays (1-D and 2-D) using Pointers
##################
Generic Pointers
##########

Summary
########
Review Questions
###############
Multiple Choice Questions
#######################
(50-100) Questions Placement Cell

Department of BS&H Page 139


NRI Institute of Technology, Pothavarappadu

You might also like