Unit 6
Unit 6
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.
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.
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();
}
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( )
{
}
And here is the output...
1234 56
1212 33
Pointer arithmetic
###################
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.
Calloc():- <alloc.h>
This is also used for allocating memory at run time.
Syntax: void *calloc(size_t nitems, size_t size);
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”
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);
}
/*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];
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.
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;
}
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