Beruflich Dokumente
Kultur Dokumente
ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
POINTERS
What is Pointer?
Pointer is a user defined data type which creates special types of variables which can hold the address of
primitive data type like char, int, float, double or user defined data type like function, pointer etc. or
derived data type like array, structure, union, enum.Pointers are used in C program to access the memory
and manipulate the address.
data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is pointing. void type pointer
works with all data types, but isn't used oftenly.
Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer
variable contains address of variable of same data type. In C language address operator & is used to
determine the address of a variable. The & (immediately preceding a variable name) returns the address
of the variable associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
1
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.
int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.printf("%u",&p); //this will also print the address
of p.
Output
Value: 5
Address: 2686778
Note: You may obtain different value of address while using this code.
In above source code, value 5 is stored in the memory location 2686778. var is just the name given to
that location.
You, have already used reference operator in C program while using scanf() function.
scanf("%d",&var);
2
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Pointer variable or simply pointer are the special types of variables that holds memory address rather
than data, that is, a variable that holds address value is called a pointer variable or simply a pointer.
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
Output
Address of c: 2686784
Value of c: 22
3
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Address of c: 2686784
Value of c: 2
1. Code int* pc; creates a pointer pc and a code int c; creates normal variable c. Pointer pc points to
some address and that address has garbage value. Similarly, variable c also has garbage value at
this point.
2. Code c=22; makes the value of c equal to 22, i.e.,22 is stored in the memory location of variable
c.
3. Code pc=&c; makes pointer, point to address of c. Note that, &c is the address of variable
c (because c is normal variable) and pc is the address of pc (because pc is the pointer variable).
Since the address of pc and address of c is same, *pc will be equal to the value of c.
4. Code c=11; makes the value of c, 11. Since, pointer pc is pointing to address of c. Value inside
address pc will also be 11.
5. Code *pc=2; change the contents of the memory location pointed by pointer pc to change to 2.
Since address of pointer pc is same as address of c, value of c also changes to 2.
int arr[4];
In arrays of C programming, name of the array always points to the first element of an array. Here,
address of first element of an array is &arr[0]. Also, arr represents the address of the pointer where it is
pointing. Hence, &arr[0] is equivalent to arr.
4
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0] is arr[0] and
value in address arr is *arr. Hence, arr[0] is equivalent to *arr.
Similarly,
In C, you can declare an array and can use pointer to alter the data of an array.
#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
s//Program to find the sum of six numbers with arrays and pointers.
um += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21
When, argument is passed using pointer, address of the memory location is passed instead of value.
5
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Output
Number1 = 10
Number2 = 5
Explanation
The address of memory location num1 and num2 are passed to function and the pointers *a and *b
accept those values. So, the pointer a and b points to address of num1 and num2 respectively. When, the
value of pointer are changed, the value in memory location also changed correspondingly. Hence,
change made to *a and *b was reflected in num1 and num2 in main function.
The exact size of array is unknown untill the compile time,i.e., time when a compier compiles code
written in a programming language into a executable form. The size of array you have declared initially
can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a
program to obtain more memory space, while running or to release space when no space is required.
Although, C language inherently does not has any technique to allocated memory dynamically, there are
4 library functions under "stdlib.h" for dynamic memory allocation.
6
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory
malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size
of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float,
i.e, 4 bytes.
free()
7
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
8
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change
memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
9
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
When an array is declared, compiler allocates sufficient amount of memory to contain all the elements
of the array. Base address which gives location of the first element is also allocated by the compiler.
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will
be stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0].
Therefore arr is containing the address of arr[0] i.e 1000.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
10
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access
the array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the aboce program, the pointer *p will print all the values stored in the array one by one. We can also
use the Base address (a in above case) to act as pointer and print all the values.
We can also have array of pointers. Pointers are very helpful in handling character array with rows of
varying length.
char *name[3]={
"Adam",
"chris",
11
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};
It is possible to declare a pointer pointing to a function which can then be used as an argument in
another function. A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
Example :
int (*sum)(); //legal declaraction of pointer to function
int *sum(); //This is not a declaraction of pointer to function
A function pointer can point to a specific function when it is assigned the name of the function.
12
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
s is a pointer to a function sum. Now sum can be called using function pointer s with the list of
parameter.
s (10, 20);
int main( )
{
int (*fp)(int, int);
fp=sum;
int s = fp(10, 15);
printf("Sum is %d",s);
getch();
return 0;
}
Output : 25
Void pointer or generic pointer is a special type of pointer that can be pointed at objects of any data
type. A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type.
Pointers defined using specific data type cannot hold the address of the some other type of variable i.e.,
it is incorrect in C++ to assign the address of an integer variable to a pointer of type float.
Example:
13
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The above problem can be solved by general purpose pointer called void pointer.
The pointer defined in this manner do not have any type associated with them and can hold the address
of any type of variable.
Example:
void *v;
int *i;
int ivar;
char chvar;
float fvar;
v = &ivar; // valid
v = &chvar; //valid
v = &fvar; // valid
i = &ivar; //valid
i = &chvar; //invalid
i = &fvar; //invalid
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of
type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that
the asterisk operator be applied twice, as is shown below in the example:
#include <stdio.h>
14
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
When the above code is compiled and executed, it produces the following result:
The rules for assigning one pointer to another are tighter than the rules for numeric types. For example,
you can assign an int value to a double variable without using a type conversion, but you can’t do the
same for pointers to these two types. Let’s see a simple C program to exemplify this.
#include <stdio.h>
int main(void)
{
int n = 5;
long double x;
int *pi = &n;
long double *pld = &x;
x = n; /* implicit type conversion */
pld = pi; /* compile-time error: assigning pointer-to-int to */
/* pointer-to-long-double */
return 0;
}
These restrictions extend to more complex types. Suppose we have the following declarations:
15
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int *pi;
int (*pa)[3]; /* pointer to an array of 3 integers */
int ar1[2][3];
int ar2[3][2];
int **p2pi; /* a pointer-to-pointer-to-int, a double pointer */
Notice that the non valid assignments all involve two pointers that don’t point to the same type.
For example, ‘pi’ points to a single int, but ‘ar1′ points to an array of three ints. Similarly, ‘pa’ points to
an array of three ints, so it is compatible with ‘ar1′, but not with ‘ar2′, which points to an array of two
ints.
The last two examples are somewhat tricky. The variable p2pi is a pointer-to-pointer-to-int, whereas ar2
is a pointer-to-array-of-two-ints (or, more concisely, pointer-to-int[2]). So p2pi and ar2 are of different
types, and therefore we can’t assign ‘ar2′ to ‘p2pi’. But ‘*p2pi’ is of type pointer-to-int, making it
compatible with ‘ar2[0]‘. Recall that ‘ar2[0]‘ is a pointer to its first element, ‘ar2[0][0]‘, making ‘ar2[0]‘
type pointer-to-int also.
In general, multiple indirection is tricky. For instance, consider the next snippet of code:
int *p1;
const int *p2;
const int **p2p;
As we have seen earlier, assigning a const pointer to a non-const pointer is invalid, because we could use
the new pointer to alter const data. But assigning a non-const pointer to a const pointer is okay, provided
that we’re dealing with just one level of indirection:
16
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
But such assignments no longer are safe when we go to two levels of indirection. If it were allowed, we
could do something like this:
But notice then non-constant pointer-to-int ‘p1′ modified constant integer n. Therefore multi-level
indirection is not allowed.
1.Incrementing Pointer :
1. Incrementing Pointer is generally used in array because we have contiguous memory in array and
we know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable
Address++ = Address
++Address = Address
Pictorial Representation :
Data Older Address stored in Next Address stored in pointer after incrementing
Type pointer (ptr++)
17
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Data Older Address stored in Next Address stored in pointer after incrementing
Type pointer (ptr++)
Note to Remember : Increment and Decrement Operations on pointer should be used when we have
Continues memory (in Array).
#include<stdio.h>
int main(){
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
#include<stdio.h>
int main(){
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
#include<stdio.h>
int main(){
float var[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];
ptr=&var;
printf("Value inside ptr : %u",ptr);
ptr=ptr+1;
printf("Value inside ptr : %u",ptr);
return 0;
}
Output :
19
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Explanation :
Address of ptr[1]
= Address of ptr[0] + (Size of Data Type)*(Size of Array)
= 1000 + (4 bytes) * (5)
= 1020
Address of Var[0]…Var[4] :
2.Decrementing a pointer:
#include<stdio.h>
20
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(){
printf("\nDifference : %d",ptr2-ptr1);
return 0;
}
Output :
Difference : 250
Explanation :
Ptr1 and Ptr2 are two pointers which holds memory address of Float Variable.
Ptr2-Ptr1 will gives us number of floating point numbers that can be stored.
Example 2:
#include<stdio.h>
struct var{
char cvar;
int ivar;
float fvar;
};
int main(){
printf("Difference= %d",ptr2-ptr1);
return 0;
}
21
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Output :
Difference = 142
Explanation :
In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
In order to compute the final value we need to use following formulae :
int *ptr , n;
ptr = &n ;
ptr = ptr + 3;
#include<stdio.h>
int main(){
ptr=ptr+3;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
Explanation of Program :
22
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
this line will store 1000 in the pointer variable considering 1000 is memory location for any of the
integer variable.
Formula :
Suppose we have subtracted “n” from pointer of any data type having initial addess as “init_address”
then after subtraction we can write –
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
#include<stdio.h>
int main(){
23
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ptr=ptr-3;
printf("New Value of ptr : %u",ptr);
return 0;
}
Output :
Formula :
Summary :
1. Pointer comparison is Valid only if the two pointers are Pointing to same array
2. All Relational Operators can be used for comparing pointers of same type
3. All Equality and Inequality Operators can be used with all Pointer types
4. Pointers cannot be Divided or Multiplied
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;
24
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
return(0);
}
#include<stdio.h>
int main()
{
int *ptr1;
float *ptr2;
return(0);
}
Explanation :
As we know Pointers can store Address of any data type, address of the data type is “Integer” so we can
compare address of any two pointers although they are of different data types.
25
JOGINPALLY B. R. ENGINEERING COLLEGE
B.Tech-I Year COMPUTER PROGRAMMING NOTES
D.Murali Mohan K. Praveen Kumar P.Sandya A. Raju
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
== Equals
!= Not Equal
#include<stdio.h>
int main()
{
int *ptr1,*ptr2;
return(0);
}
Output :
26