Professional Documents
Culture Documents
Pointer in Java
Pointer in Java
2. Let us consider it‘s Corresponding address be 65624 and the Value stored in
variable „i‟ is 5
3. The address of the variable „i‟ is stored in another integer variable whose
j =&i;
i.e.
j = Address of i
Here j is not ordinary variable; it is special variable and called pointer variable as it
1
Variable Name Variable Value Variable Address
I 5 65524
J 65524 65522
#include <stdio.h>
intmain()
{
int*ptr, i;
i =11;
return0;
}
2
pointer variable name and asterisk can contain whitespace because whitespace is
ignored by compiler.
int*ptr;
int* ptr;
int* ptr;
All the above syntax are legal and valid. We can insert any number of spaces or
blanks inside declaration. We can also split the declaration on multiple lines.
1. Unlike ordinary variables pointer is special type of variable which stores the
2. Pointer can only store the whole or integer number because address of any
Pointer Summary:
2. When we declare integer pointer then we can only store address of integer
3
3. Similarly if we declare character pointer then only the address of character
Understanding pointers in c?
In the previous chapter we have learnt about Basic Concept of Pointer. In this
We know that –
2. Since Pointer is also a kind of variable , thus pointer itself will be stored at
2 Types of Variables:
2. Complex Variable that stores address of simple variable i.e. pointer variables
Example #1:
#include<stdio.h>
4
intmain()
{
int a =3;
int*ptr;
ptr =&a;
return(0);
}
Explanation of Example:
Example #2:
#include<stdio.h>
intmain()
{
int a =3;
int*ptr,**pptr;
ptr =&a;
pptr = &ptr;
return(0);
}
5
Explanation of Example
6
lets take an example –
#include<stdio.h>
voidmain()
{
int n =10;
printf("\nValue of n is : %d",n);
printf("\nValue of &n is : %u",&n);
}
Output:
Value of n is: 10
Consider the above example, where we have used to print the address of the
In order to print the variable we simply use name of variable while to print the
#include<stdio.h>
int main()
{
int i =5;
7
int*ptr;
ptr =&i;
printf("\nAddress of i : %u",&i);
printf("\nValue of ptr is : %u",ptr);
return(0);
}
After declaration memory map will be like this –
int i =5;
int*ptr;
after Assigning the address of variable to pointer , i.e after the execution of this
statement –
ptr =&i;
Address of literals
8
In C programming using address operator over literal will throw an error. We cannot
use address operator on the literal to get the address of the literal.
&75
Only variables have an address associated with them, constant entity does not have
literal –
&('a')
Address of expressions
(a+b) will evaluate addition of values present in variables and output of (a+b)is
&(a+b)
1. When we use variable in program then Compiler keeps some memory for
2. The address given to the variable is Unique with that variable name
9
Explanation:
address.
2. In the above program ―i‖ is name given for memory location for
2. Variable may be integer, character, float but the address of the variable
Compiler.
3. If we run same program in any other IDE then the output may differ.
#include<stdio.h>
intmain()
{
int a =10,*ptr;
ptr =&a;
10
printf("\nSize of Integer Pointer : %d",sizeof(ptr));
return(0);
}
Output :
#include<stdio.h>
intmain()
{
char a ='a',*cptr;
cptr =&a;
printf("\nSize of Character Pointer : %d",sizeof(cptr));
return(0);
}
Output :
#include<stdio.h>
intmain()
{
float a =3.14,*fptr;
fptr =&a;
printf("\nSize of Character Pointer : %d",sizeof(fptr));
return(0);
}
Output :
11
Size of Float Pointer: 2
Size calculation
Consider the following memory map before declaring the variable.In the memory
Whenever we declare any variable then random block of memory is chosen and
Similarly whenever we declare any pointer variable then random block of memory
will be used as pointer variable which can hold the address of another variable.
Program
#include<stdio.h>
12
intmain()
{
int*iptr =NULL;
float*fptr =NULL;
char*cptr =NULL;
return0;
}
Output :
Explanation
4. For Borland C/C++ Compiler, for storing integer value 2 bytes are required.
13
Compiler Size of Integer Size of Integer Pointer
Program :
#include<stdio.h>
intmain(){
intfar *ptr;
printf("Size of Integer Far Pointer : %d",sizeof(ptr));
return(0);
}
Output :
Program :
#include<stdio.h>
typedefstructXYZ{
intfar *fptr;
doubledvar;
unsignedcharch;
}xyz;
14
intmain(){
xyz *ptr=(XYZ *)1000;
printf("Size of Pointer to structure : %d",sizeof(ptr));
return(0);
}
Output :
In order to create pointer to a variable we use ―*‖ operator and to find the address
Don‘t Consider ―&‖ and ―*‖ operator as Logical AND and Multiplication Operator in
Case of Pointer.
Important Notes :
15
#include<stdio.h>
intmain()
{
int n =20;
printf("\nThe address of n is %u",&n);
printf("\nThe Value of n is %d",n);
printf("\nThe Value of n is %d",*(&n));
}
Output:
The Value of n is 20
The Value of n is 20
m = * ( &n )
= * ( Address of Variable 'n')
= * ( 1000 )
= Value at Address 1000
= 20
16
What Does following declaration tells compiler ?
int*ptr;
1. ‗ptr‘ is declared as that ‗ptr‘ will be used only for storing the address of the
Memory
Declaration Explanation
Required
data_type *<pointer_name>;
Explanation:
data_type
Asterisk(*)
17
Asterisk is called as Indirection Operator
pointer_name
int *p;
int * p;
int * p;
Example of Declaring Integer Pointer :
int n =20;
int*ptr;
char ch ='A';
char*cptr;
float*fptr;
18
pointer=&variable;
2. Declare another Variable with Same Data Type as that of Pointer Variable.
variable.
#include<stdio.h>
intmain()
{
int a;// Step 1
int*ptr;// Step 2
a =10;// Step 3
ptr =&a;// Step 4
return(0);
}
19
Now ―ptr‖ will contain the address of the variable ―a‖ .
Note:
#include<stdio.h>
intmain()
{
int a =10;
int*ptr;
ptr =&a;
printf("\nValue of ptr : %u",ptr);
return(0);
}
Output :
3. When used with Pointer variable, it refers to variable being pointed to,this is
20
1. Dereferencing Operation is performed to access or manipulate data contained
21
Variable Value in it
num 50
&num 1002
ptr 1002
*ptr 50
22
4. A void pointer is a C convention for a raw address.
5. The compiler has no idea what type of object a void Pointer really points to ?
void * pointer_name;
char cnum;
int inum;
float fnum;
Explanation:
void*ptr;
3. When we assign address of integer to the void pointer, pointer will become
Integer Pointer.
5. Similarly we can assign address of any data type to the void pointer.
23
6. It is capable of storing address of any data type
Scenario Behavior
float*ptr;
int num;
program. We cannot use float pointer to store the integer pointer so So in order to
void Pointer.
24
Consider this example –
*((int*)ptr)
Integer *((int*)ptr)
Charcter *((char*)ptr)
Floating *((float*)ptr)
#include<stdio.h>
intmain()
25
{
int inum =8;
float fnum =67.7;
void*ptr;
ptr =&inum;
printf("\nThe value of inum = %d",*((int*)ptr));
ptr =&fnum;
printf("\nThe value of fnum = %f",*((float*)ptr));
return(0);
}
Output :
ptr =&inum;
Here we are assigning the address of integer variable to void pointer so that void
ptr =&fnum;
And now we are storing the address of floating point variable to void pointer , thus
Pointer :
26
Pointer is the variable that stores the address of another variable .
int main(void)
{
int num = 0;
void *ptr;
num = 15;
ptr = #
/* Output the size */
Output :
Address Arithmetic
27
According to C and C++ language standards, the result address must remain
strictly within the bounds of a single array object (or just after it). Adding or
subtracting from a pointer moves it by a multiple of the size of the data type it
points to. For example, assume we have a pointer to an array of 4-byte integers.
Incrementing this pointer will increment its value by 4 (the size of the element).
This effect is often used to increment a pointer to point at the next element in a
type has no size, and thus the pointed address cannot be added to. However, there
Pointers and integer variables are not interchangeable. Null constant is the
only exception from this rule: it can be assigned to the pointer, and the pointer can
be compared to null constant. As a rule, to show that null is a special value for the
Pointer arithmetic provides the programmer with a single way of dealing with
different types: adding and subtracting the number of elements required instead of
the actual offset in bytes. In particular, the C definition explicitly declares that the
syntax A[i], which is the i-th element of the array A, is equivalent to *(A+i), which
is the content of the element pointed by A+i. This also implies that i[A] is
equivalent to A[i].
At the same time, powerful pointer arithmetic can be a source of errors. Address
arithmetic is a restrictive stage in the process of mastering 64-bit systems for the
old C/C++ program code can contain a lot of errors relating to the use of pointers.
28
To learn more about this problem see the article "20 issues of porting C++ code on
computer languages (for example, Java or C#) do not permit direct access to
Pointer Arithmetic
knowledge of pointer. In this topic we will study how the memory addresses change
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double*
is always 2 bytes. But when we perform any arithmetic function like increment on
a pointer, changes occur as per the size of their primitive data type.
Type Size(bytes)
Char 1
Long 4
Float 4
Double 8
29
long double 10
Now lets take a few examples and understand this more clearly.
int* i;
i++;
In the above case, pointer will be of 2 bytes. And when we increment it, it will
float* i;
i++;
In this case, size of pointer is still 2 bytes. But now, when we increment it, it will
double* i;
i++;
Similarly, in this case, size of pointer is still 2 bytes. But now, when we increment
The concept of pointer arithmetic remains exact same, but the size of pointer and
of 4 bytes.
30
Type Size(bytes)
Char 2
Long 8
Float 8
Double 16
Consider below table, We have declared some of the variables and also assumed
Expression Result
31
Expression Result
Above table clearly shows that we can add or subtract address and integer number
to get valid address. We can even subtract two addresses but we cannot add two
Incrementing Pointer :
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable
32
Pictorial Representation :
incremented by 2.
#include<stdio.h>
intmain(){
int*ptr=(int*)1000;
33
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return0;
}
Output :
#include<stdio.h>
intmain(){
double*ptr=(double*)1000;
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return0;
}
Output :
#include<stdio.h>
intmain(){
float var[5]={1.1f,2.2f,3.3f};
float(*ptr)[5];
ptr=&var;
printf("Value inside ptr : %u",ptr);
ptr=ptr+1;
34
printf("Value inside ptr : %u",ptr);
return0;
}
Output :
Explanation :
Address of ptr[1]
= 1020
Address of Var[0]…Var[4] :
35
Address of var[0] = 1000
C decrementing pointer
Example :
Explanation :
36
Decrementing a pointer to an integer data will cause its value to be
decremented by 2
#include<stdio.h>
intmain(){
float*ptr1=(float*)1000;
float*ptr2=(float*)2000;
printf("\nDifference : %d",ptr2-ptr1);
return0;
}
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.
#include<stdio.h>
struct var{
char cvar;
int ivar;
37
float fvar;
};
intmain(){
struct var *ptr1,*ptr2;
ptr1 =(struct var *)1000;
ptr2 =(struct var *)2000;
printf("Difference= %d",ptr2-ptr1);
return0;
}
Output :
Difference = 142
Explanation:
C pointer addition
int*ptr , n;
ptr =&n ;
ptr = ptr +3;
Live Example 1 : Increment Integer Pointer
#include<stdio.h>
intmain(){
int*ptr=(int*)1000;
ptr=ptr+3;
printf("New Value of ptr : %u",ptr);
return0;
}
Output :
Explanation of Program :
int*ptr=(int*)1000;
this line will store 1000 in the pointer variable considering 1000 is memory location
Formula:
39
float*ptr=(float*)1000;
Suppose we have subtracted ―n‖ from pointer of any data type having initial addess
int*ptr , n;
ptr =&n ;
ptr = ptr -3;
Live Example 1 : Decrement Integer Pointer
#include<stdio.h>
intmain(){
int*ptr=(int*)1000;
ptr=ptr-3;
printf("New Value of ptr : %u",ptr);
return0;
}
Output :
Formula:
40
ptr = ptr -3*(sizeof(integer))
=1000-3*(2)
=1000-6
=994
Summary:
Pointer-Pointer= Integer
C subtracting pointers
#include<stdio.h>
intmain()
{
int num ,*ptr1 ,*ptr2 ;
ptr1 =&num ;
ptr2 = ptr1 +2;
printf("%d",ptr2 - ptr1);
return(0);
}
Output :
41
ptr1 stores the address of Variable num
Important Observations :
Remember the following formula while computing the difference between two
pointers –
42
=4
Step 2 : Finding Actual Difference (Technical Difference)
objects
3. Suppose Both pointers of float the they will be differed numerically by 8 and
Technically by 2 objects
and
Integer 2 1
Float 4 1
Character 1 1
43
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
#include<stdio.h>
intmain()
{
int*ptr1,*ptr2;
ptr1 =(int*)1000;
ptr2 =(int*)2000;
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
return(0);
}
Pointer Comparison of Different Data Types :
#include<stdio.h>
intmain()
{
int*ptr1;
float*ptr2;
ptr1 =(int*)1000;
ptr2 =(float*)2000;
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
44
return(0);
}
Explanation :
types.
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
== Equals
!= Not Equal
#include<stdio.h>
intmain()
45
{
int*ptr1,*ptr2;
ptr1 =(int*)1000;
ptr2 = ptr1/4;
return(0);
}
Output :
intmain(){
int num =10;
int*ptr;
ptr =#
return(0);
}
46
2. Pointer Variable Can be Assigned the value of another Pointer Variable
int*sptr,*tptr;
sptr =#
tptr = sptr;
3. Pointer Variable Can be initialized with zero or NULL value.
int*sptr,*tptr;
sptr =0;
tptr =NULL;
4. Pointer variable Can be Perform Pre/Post fix Increment/Decrement Operation
int arr[20];
int*ptr;
ptr =&arr;
ptr++;
5. Integer value can be added or Subtracted from Pointer variable
int arr[20];
int*ptr;
ptr =&arr;
ptr = ptr +2;//arr[2] will be accessed
6. When two Pointer points to same array then one Pointer variable can be
7. Two Pointers pointing to objects of same data type then they can be
int*ptr;
ptr =100;//Illegal
9. Pointer Variable cannot be multiplied by Constant
47
int*ptr;
ptr = ptr *6;//Illegal
C pointer invalid operations
decrement but still we have some more arithmetic operations that cannot be
performed on pointer –
#include<stdio.h>
intmain()
{
int var =10;
int*ptr1 =&i;
int*ptr2 =(int*)2000;
printf("%d",ptr1+ptr2);
return0;
}
Output :
Compile Error
48
2. Multiplication of Pointer and number :
#include<stdio.h>
intmain()
{
int var =10;
int*ptr1 =&i;
int*ptr2 =(int*)2000;
printf("%d",ptr1*var);
return0;
}
Output :
Compile Error
#include<stdio.h>
int main(){
int var =10;
int*ptr1 =&i;
int*ptr2 =(int*)2000;
printf("%d",ptr1*ptr2);
return0;
}
Output :
Compile Error
4. Modulo Operation
49
int *ptr2 = (int *)2000;
int var = ptr2 % ptr1;
5. Division of pointer
#include<stdio.h>
intmain()
{
int*ptr1,*ptr2;
ptr1 =(int*)1000;
ptr2 = ptr1/4;
return(0);
}
Output :
#include<stdio.h>
intmain(){
50
int i=5,j=10;
int*p=&i;
int*q=&j;
printf("%d",p|q);
return0;
}
7.Negation Operation on Pointer
#include<stdio.h>
intmain(){
int i=5;
int*ptr=&i;
printf("%d",~ptr);
return0;
}
Summary at a glance :
Value at operator is denoted by ‗*‘. In C Star(*) operator is used for two purposes –
51
Multiplication
Meaning of (*++ptr)
int n = 20 , *ptr ;
ptr = &n;
printf("%d",*++ptr);
Explanation :
52
Calculation of Answer :
* ++ptr = *(++ptr )
= *( 3060 )
= Value Stored at Location 3060
Live Program :
#include<stdio.h>
intmain()
{
int n =20,*ptr ;
ptr =&n;
printf("%d",*++ptr);
return(0);
}
Output :
Note :
53
1. This operation should not be used in normal operation.
#include<stdio.h>
intmain()
{
int arr[5]={10,20,30,40,50};
int*ptr ;
ptr =&arr;
printf("%d",*++ptr);
return(0);
}
Output :
20
54
1. „++‟ and „*‟ both are having equal precedence and priority. Associativity of
these two operators is from right to left (Expression evaluated from R->L)
2. Both the operators are Unary so they will only works on single operand
3. Dereference operator ‗*‘ will get chance for execution before pre increment
operator ‗++‘.
Visual Understanding
Calculation of Answer :
Consider that variable ‗num‘ is stored at location address 3058 to which pointer ‗ptr‘
++*ptr = ++ ( *ptr )
= ++ ( *3058 )
= ++ ( 20 )
= 21
* Operator will de-reference pointer to get value stored at that address.(i.e 20)
++ ( *3058 )
++ ( 20 )
55
Pre-increment on 20 will perform increment first then assignment
#include<stdio.h>
intmain()
{
int n =20,*ptr ;
ptr =&n;
printf("%d",++*ptr);
return(0);
}
Output :
21
3. When used with Pointer variable, it refers to variable being pointed to,this is
Variable Value in it
num 50
&num 1002
57
ptr 1002
*ptr 50
Incrementing Pointer :
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable
Pictorial Representation :
58
Data Older Address Next Address stored in pointer
Type stored in pointer after incrementing (ptr++)
incremented by 2 .
#include<stdio.h>
intmain(){
int*ptr=(int*)1000;
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return0;
}
Output :
59
#include<stdio.h>
intmain(){
double*ptr=(double*)1000;
ptr=ptr+1;
printf("New Value of ptr : %u",ptr);
return0;
}
Output :
#include<stdio.h>
intmain(){
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);
return0;
}
Output :
60
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] :
float*ptr;
int num;
program. We cannot use float pointer to store the integer pointer so So in order to
void Pointer.
*((int*)ptr)
62
Following table will summarize all details –
Integer *((int*)ptr)
Charcter *((char*)ptr)
Floating *((float*)ptr)
#include<stdio.h>
intmain()
{
int inum =8;
float fnum =67.7;
void*ptr;
ptr =&inum;
printf("\nThe value of inum = %d",*((int*)ptr));
ptr =&fnum;
printf("\nThe value of fnum = %f",*((float*)ptr));
return(0);
}
Output :
ptr =&inum;
63
printf("\nThe value of inum = %d",*((int*)ptr));
Here we are assigning the address of integer variable to void pointer so that void
ptr =&fnum;
printf("\nThe value of fnum = %f",*((float*)ptr));
And now we are storing the address of floating point variable to void pointer , thus
*ptr++ means
++*ptr means
Answer :
No
2. Suppose ptr is Pointing to the Integer Variable having value 10. [ num = 10 ]
64
4. *ptr++ means Grab the Value of (*ptr) And then Increment It , which
#include<stdio.h>
intmain()
{
int num =10;
int*ptr;
ptr =#
printf("Value of ++*ptr : %d",++*ptr);
65
return(0);
}
Output :
11
#include<stdio.h>
intmain()
{
int num =10;
int*ptr;
ptr =#
printf("Value of *ptr++ : %d",*ptr++);
return(0);
}
Output :
10
Conclusion :
Program :
#include<stdio.h>
#include<conio.h>
voidmain()
{
int i =50;
int**ptr1;
66
int*ptr2;
clrscr();
ptr2 =&i;
ptr1 =&ptr2;
printf("\nThe value of **ptr1 : %d",**ptr1);
printf("\nThe value of *ptr2 : %d",*ptr2);
getch();
}
Output :
4. Similarly ‗ptr1‘ is also a pointer variable which stores the address of Pointer
variable [i.e ptr2 stores address of integer variable while ptr1 stores address
5. So
67
**ptr1 is used to access actual value.
int **ptr2ptr;
ptr =#
ptr2ptr =&ptr;
*ptr 45
**ptr2ptr 45
ptr &n
68
ptr2ptr &ptr
Notes :
Live Example :
#include<stdio.h>
intmain()
{
int num =45,*ptr ,**ptr2ptr ;
ptr =#
ptr2ptr =&ptr;
printf("%d",**ptr2ptr);
return(0);
}
Output :
45
Syntax :
Example :
69
int n =30;
constint ptr;
ptr =&n;
What does it means ?
4. We can change address of such pointer so that it will point to new memory
location.
*ptr =20;
ptr++
#include<stdio.h>
intmain()
{
int num[2]={10,20};
constint*ptr;
ptr =&num[0];
printf("%d",*ptr);
return(0);
}
70
Output:
10
#include<stdio.h>
intmain()
{
int num[2]={10,20};
constint*ptr;
ptr =&num[0];
ptr++;
printf("%d",*ptr);
return(0);
}
Output :
20
#include<stdio.h>
intmain()
{
int num[2]={10,20};
constint*ptr;
ptr =&num[0];
*ptr =30;
printf("%d",*ptr);
71
return(0);
}
Output :
Compile Error
Syntax Declaration :
72
*ptr =20;// Valid Statement
ptr ++;// Invalid Statement
Explanation :
fixed
4. But we can Change the Value at 2001 i.e we can change value 15 to 20
#include<stdio.h>
intmain()
{
int num[2]={10,20};
int*const ptr =&num[0];
printf("%d",*ptr);
return(0);
}
Output :
73
10
Explanation :
cause error.
int*const ptr;
ptr =&num[0];
above statements will cause error.
#include<stdio.h>
intmain()
{
int num[2]={10,20};
int*const ptr =&num[0];
ptr++;
printf("%d",*ptr);
return(0);
}
Output :
74
Example 3 : We can change value stored at address.
#include<stdio.h>
intmain()
{
int num[2]={10,20};
int*const ptr =&num[0];
*ptr =30;
printf("%d",*ptr);
return(0);
}
75
Output :
30
Summary
array
int a[10];
int a[10][10];
Let
1. x is an array ,
2. i is subscript variable
x[i] = *(x+i)
= *(i+x)
= i[x]
Proof of the above Formula :
= *x
Thus we have concluded that , first element of array is equivalent to *x .
main()
int *ptr,i ;
ptr = x
for(i=0;i<5;i++)
77
printf("nAddress : %u",&x[i]);
printf("nElement : %d",x[i]);
printf("nElement : %u",*(x+i));
printf("nElement : %d",i[x]);
printf("nElement : %d",*ptr);
Output :
Address : 7600
Element : 1
Element : 1
Element : 1
Element : 1
Address : 7602
Element : 2
Element : 2
Element : 2
Element : 2
Address : 7604
Element : 3
Element : 3
Element : 3
Element : 3
Address : 7606
78
Element : 4
Element : 4
Element : 4
Element : 4
Address : 7608
Element : 5
Element : 5
Element : 5
Element : 5
x[i] *(x + i)
i[x] *ptr
79
In this example
#include<stdio.h>
intmain()
{
int i;
char*arr[4]={"C","C++","Java","VBA"};
char*(*ptr)[4]=&arr;
for(i=0;i<4;i++)
printf("Address of String %d : %u\n",i+1,(*ptr)[i]);
return0;
}
Output :
80
Address of String1=178
Address of String2=180
Address of String3=184
Address of String4=189
#include<stdio.h>
intmain()
{
int i;
char*arr[4]={"C","C++","Java","VBA"};
char*(*ptr)[4]=&arr;
for(i=0;i<4;i++)
printf("String %d : %s\n",i+1,(*ptr)[i]);
return0;
}
Output :
String1= C
String2= C++
String3= Java
String4= VBA
#include<stdio.h>
81
intmain()
{
int i;
char*arr[4]={"C","C++","Java","VBA"};
char*(*ptr)[4]=&arr;
printf("%s",++(*ptr)[2]);
return0;
}
Output:
ava
function pointer.
Example :
#include<stdio.h>
void display();
intmain()
{
void*(*ptr)();
ptr =&display;
(*ptr)();
return(0);
}
82
void display()
{
printf("Hello World");
}
Output :
Hello World
Explanation of C Snippet :
Now in the above program we have just called function display(), and we get output
as ―Hello World‖.
Consider Scenario using pointer , We should follow following 3 steps to use pointer
to call function –
void*(*ptr)();
83
Above declaration tells us ….
Declare Pointer variable that can store address of function which does not return
ptr =&display;
(*ptr)();
using (*ptr)() we can call function display();
(*ptr)()=(*ptr)();
=(*&display)();
=(display)();
= display();
thus (*ptr)() is as good as calling function.
Return Type :
None
void*(*ptr)(); ptr =&display; (*ptr)();
Parameter :
None
Return Type :
Integer int result;
int*(*ptr)(); ptr =&display;
Parameter : result =(*ptr)();
None
84
Float result =(*ptr)();
Parameter :
None
Return Type :
Char char result;
char*(*ptr)(); ptr =&display;
Parameter : result =(*ptr)();
None
Example 1 : Function having two Pointer Parameters and return type as Pointer
#include<stdio.h>
char* getName(int*,float*);
intmain()
{
char*name;
int num =100;
float marks =99.12;
char*(*ptr)(int*,float*);
ptr=&getName;
name =(*ptr)(&num,&marks);
printf("Name : %s",name);
return0;
}
//-------------------------------------
char*getName(int*ivar,float*fvar)
{
char*str="www.c4learn.com";
str = str +(*ivar)+(int)(*fvar);
return(str);
}
85
Output :
.c4learn.com
#include<stdio.h>
int display();
int(*arr[3])();
int(*(*ptr)[3])();
intmain(){
arr[0]=display;
arr[1]=getch;
ptr=&arr;
printf("%d",(**ptr)());
(*(*ptr+1))();
return0;
}
int display(){
int num =25;
return num;
}
Output :
25
Explanation :
int(*arr[3])();
86
Array stores address of functions
Array stores address of function having integer as return type and does
int(*(*ptr)[3])();
arr[0]= display;
arr[1]= getch;
Step 4 : Store address of function Array to Function Pointer
ptr =&arr;
(**ptr)();
(*(*ptr+1))();
Pointer :
87
Accessing Integer using char pointer : will Lose Binary Data !
2. De-Reference Means Accessing the data from the address being stored in
pointer variable
Suppose we assign the address of integer variable to the character pointer then
some part of value will be lost while accessing the variable using character data
type.
#include<stdio.h>
intmain()
{
int a=320;
88
char*ptr;
ptr=(char*)&a;
printf("%d",*ptr);
return(0);
}
Output of the Code :
64
respectively
320=000000010100000
We have already studied the different type of pointer in C. In this tutorial we will be
89
2. NULL pointer points the base address of segment.
3. In case, if you don‘t have address to be assigned to pointer then you can
#define NULL 0
#include<stdio.h>
intmain(){
int num =NULL;
printf("Value of Number ",++num);
return0;
}
Above program will never print 1, so keep in mind that NULL should be used only
Visual Representation
90
Below are some of the variable representations of NULL pointer.
float*ptr =(float*)0;
char*ptr =(char*)0;
double*ptr =(double*)0;
char*ptr ='\0';
int*ptr =NULL;
you can see that we have assigned the NULL to only pointers.
#include <stdio.h>
intmain()
{
int*ptr =NULL;
printf("The value of ptr is %u",ptr);
return0;
}
Output :
You can find some of the frequently asked questions about NULL pointer here
91
char * and char [] both are used to access character array, Though functionally
both are same , they are syntactically different. See how both works in order to
access string.
Consider following sample example for storing and accessing string using character
array –
In the example – String ―Hello‖ is stored in Character Array ‗a‘. Character array is
Form after Initialization. We have not specified Array Size in this example.Each
a[0] = 'H'
a[1] = 'E'
a[2] = 'L'
a[3] = 'L'
a[4] = 'O'
a[5] = '\0'
It will Looks Like This …
92
Suppose we have to find out a[3] then firstly compiler will check whether ‗a‘ is
Array or Pointer ? If ‗a‘ is Array Variable then It starts at the location ―a‖, goes three
elements past it, and returns the character there.In this method element is
accessed Sequentially
String ―Hello‖ will be stored at any Anonymous location in the form of array. We
even don‘t know the location where we have stored string, However String will have
Syntax of Char *a :
char *a = "HELLO";
We have declared pointer of type character i.e pointer variable is able to hold the
character pointer variable. ‗a‘ Stores Base Address of the Anonymous Array
[Unknown Array]
In Short if ‗a‘ is a pointer, it starts at the location ―a‖, gets the pointer value there,
93
adds 3 to the pointer value, and gets the character pointed to by that value
Before We Learn How to Read Complex Array we should first know precedence and
associative .
expressions
applied
Before Reading Article You Should know Precedence and Associative Table
Data Type 3 –
* Pointer operator
94
Data type Type of Pointer
How to Read ?
char (* ptr)[5]
Step 1 :
Step 2 :
Between Pair of Brackets again we have to decide which one has highest
95
Step 3 :
Write 3 under []
Step 4 :
Read it as –
ptr is pointer to a one dimensional array having size five which can store
We all know that pointer is used to store the address of a variable. Pointer
Variable stores the address of variable. Below are some of the common mistakes
96
int* ptr , m =100;
Correction :
1. ptr is pointer variable which is used to store the address of the variable.
2. Pointer Variable ―ptr‖ contain the address of the variable of type „int‟ as
pointer variable
ptr = &m ;
We are assigning the value to the pointer variable. We all know that pointer is
special kind of variable which is used to store the address of another variable. So
We are going to update the value stored at address pointed by uninitialized pointer
ptr = &n;
97
*ptr = m ;
Firstly initialize pointer by assigning the address of integer to Pointer variable. After
De-referencing pointer is process of getting the value from the address to whom
ptr =&m ;
printf("%d",ptr);
In the above example, You will not get any compiler or run time error but it is
int*ptr,m;
ptr =&m;
Best practice while using pointer is to initialize pointer before using it.
We can assign any valid address to pointer variable but if you assign the address of
un-initialized variable to pointer then it will print garbage value while de-referencing
it.
Re-commanded Article : How storage class determines the default initial value
98
We cannot compare two pointer variables. Because variables may have random
char str1[10],str2[10];
char*ptr1 = str1;
char*ptr2 = str2;
modifying the value of the pointer, so that the pointer still points to the
pointer.
#include<stdlib.h>
{
char*ptr =malloc(Constant_Value);
.......
.......
99
.......
free(ptr);/* ptr now becomes a dangling pointer */
}
We have declared the character pointer in the first step. After execution of some
pointer.
Problem : If any pointer is pointing the memory address of any variable but after
some variable has deleted from that memory location while pointer is still pointing
such memory location. Such pointer is known as dangling pointer and this
#include<stdlib.h>
{
char *ptr = malloc(Constant_Value);
.......
.......
.......
free (ptr); /* ptr now becomes a dangling pointer */
ptr = NULL /* ptr is no more dangling pointer */
}
After de-allocating memory, initialize pointer to NULL so that pointer will be no
longer dangling. Assigning NULL value means pointer is not pointing to any memory
location
100
Way 2 :Out of Scope
#include<stdlib.h>
void main()
{
char *ptr = NULL;
.....
.....
{
char ch;
ptr = &ch;
}
..... /* dp is now a dangling pointer */
}
1. Character Pointer is Declared in the first Step.
inner block .
becomes “Dangling”
101
Attempts to read from the pointer may still return the correct value (1234) for a
while after calling func, but any functions called thereafter will overwrite the stack
storage allocated for num with other values and the pointer would no longer work
correctly. If a pointer to num must be returned, num must have scope beyond the
Pointer is used for different purposes. Pointer is low level construct in programming
which is used to perform high level task. Some of the pointer applications are listed
below
First pointer application is to pass the variables to function using pass by reference
scheme.
void interchange(int*num1,int*num2)
{
int temp;
temp =*num1;
*num1 =*num2;
*num2 =*num1;
}
Pointer can be used to simulate passing parameter by reference. Pointer is used to
pass parameter to function. In this scheme we are able to modify value at direct
memory location.
102
intmain()
{
int a[5]={1,2,3,4,5};
int*ptr;
ptr = a;
for(i=0;i<5;i++){
printf("%d",*(ptr+i));
}
return(0);
}
We can access array using pointer. We can store base address of array in pointer.
ptr = a;
for(i=0;i<5;i++){
printf("%d",*(ptr+i));
We can use pointer to allocate memory dynamically. Malloc and calloc function is
#include <stdio.h>
#include <stdlib.h>
103
intmain()
{
char*str;
str =(char*)malloc(15);
strcpy(str,"mahesh");
return(0);
}
consider above example where we have used malloc() function to allocate memory
dynamically.
struct student {
char name[10];
int rollno;
};
Suppose we want to pass the above structure to the function then we can pass
104
2. Provides effective way of implementing the different data structures such as
tree,graph,linked list
105
Add numbers using function pointer
#include<stdio.h>
intmain()
{
int num1 =10;
int num2 =20;
int result;
int*(*ptr)(int,int);
ptr =∑
result =(*ptr)(num1,num2);
printf("Addition : %d",result);
return(0);
}
After you write whole code, just erase line in which we have called function
int*(*ptr)(int,int);
means –
Declare pointer variable which is capable of storing address of function which have
ptr =∑
result =(*ptr)(num1,num2);
result =(*ptr)(num1,num2);
result =(*&sum)(num1,num2);
result =(*&sum)(num1,num2);
result =(sum)(num1,num2);
107
result = sum(num1,num2);
Pointer Arithmetic
Because most ISAs use the same number of bits as integers, it's not so uncommon
Here's an example.
In general, this is one of the pitfalls of C. Arbitrary pointer casting allows you to
Unfortunately, this is not good for safe programs. In a safe programming language
(say, Java), the goal is to access objects from pointers only when there's an object
there. Furthermore, you want to call the correct operations based on the object's
type.
Arbitrary pointer casting allows you to access any memory location and do anything
you want at that location, regardless of whether you can access that memory
108
int arr[ 10 ] ;
What type does arr have? You might say "it's an int array". And, so it is.
integer pointer.
OK, now what do you think of arr[ i ]? What is that? (Assume i is some int). You
might say, it's the ith element of the array. That's correct too. What type
It's an int! (Beginning programming students often think arr[ i ] is not the same
as an int, because it uses brackets. It takes a while to convince them they have the
In particular:
arr[ i ] == * ( arr + i )
Let's take a closer look at arr + i. What does that mean? arr is a pointer to arr[ 0
109
We assume that each int takes up 4 bytes of memory. If arr is at address 1000,
then arr + 1 is address 1004, arr + 2 is address 1008, and in general, arr + i is
Now that you see the diagram, something may strange. Why is arr + 1 at address
That's pointer arithmetic in action. arr + 1 points to one element past arr. arr +
3 is points to 3 elements past arr. Thus, arr + i points to i elements past arr.
The idea is to have arr + i point to i elements after arr regardless of what type of
Suppose the array had contained short where a short is only 2 bytes. If arr is at
i).
Notice that arr + 1 is now 2 bytes after arr and arr + 2 is 4 bytes. When we had
an int array, arr + 1 was 4 bytes after arr and arr + 2 was 8 bytes afterwards.
Why is there a difference? What's the differnce between arr before and now?
The difference is in the type. Before, arr had (roughly) type int * and now arr has
type short *.
110
In C, a pointer is not only an address, it tells you what (in principle) the data type
at that address is. Thus, int * is a pointer to an int. Not only does it tell you the
data type, but you can also determine the data type's size.
You can find out the data type's size with the sizeof() operator.
That's important, because that's how pointer arithmetic computes address. It uses
the size of the data type, which it knows from the pointer's type.
Here's the formula for computing the address of ptr + i where ptr has type T *.
T can be a pointer
How does pointer arithmetic work if you have an array of pointers, for example:
int * arr[ 10 ] ;
In this case, arr has type int **. Thus, T has type int *. All pointers have the
= addr( ptr ) + [ 4 * i ]
int arr[ 10 ] ;
int arr[ 10 ] ;
int * ptr ;
// code here
// code here
}
112
Thus, it becomes arr becomes a pointer variable.
Why doesn't this cause problems? After all, won't we pass arr as an argument?
Yes, it is. However, we pass a copy of the address to arr the parameter. Thus, the
copy can be manipulated while the original pointer address that was passed during
Subtraction
We can also compute ptr - i. For example, suppose we have an int array called arr.
int arr[ 10 ] ;
int * p1, * p2 ;
p2 = p1 - 2 ; // p1 == & arr[ 1 ]
We can have a pointer point to the middle of the array (like p1). We can then
As it turns out, we can even point way past the end of the array.
int arr[ 10 ] ;
int * p1, * p2 ;
113
p2 = arr - 100 ; // p1 == & arr[ -100 ]
The compiler still computes an address, and does not core dump. For example,
if arr is address 1000ten, then p1 is address 1400ten and p2 is address 600ten. The
compiler still uses the formula for pointer arithmetic to compute the address.
This is why it's usually important to keep track of the array size and pass it in as a
parameter. When you're in a function, you can't tell the size of the array. All you
have is a pointer, and that's it. No indication of how big that array is.
If you try to compute the array's size using sizeof, you just get 4.
// Prints 4
int arr2[ 10 ] ;
// Prints 40
114
If you declare a local array (not using dynamic memory allocation), you can get the
size of the array. However, once you pass that array, all that's passed is the
int arr[ 10 ][ 12 ] ;
What type is arr? You may have been told that it's int **, but that's incorrect. Two
dimensional arrays (as declared above) are contiguous in memory. If you create an
int * arr[ 10 ] ;
then, arr has type int ** (or at least has a type compatible with int **).
The type is rather complicated, and is due to the fact that arr[ 0 ] = & arr[ 0 ][ 0
Pointer arithmetic says that arr + i gives you & arr[ i ], yet this skips an entire
row of 12 elements, i.e., skips 48 bytes times i. Thus, if arr is address 1000ten,
If the array's type were truly int **, pointer arithmetic would say the address
arrays
115
The actual type for a two-dimensional array, is declared as:
int (*ptr)[ 10 ] ;
arithmetic, it can compute the size of the array and handle it correctly. The
parentheses are NOT optional above. Without the parentheses, ptr becomes an
If you have a conventional two dimensional array, and you want to compute the
address for arr[ row ][ col ] and you have ROWS rows (where ROWS is some
constant) and COLS columns, then the formula for the address in memory is:
addr( & arr[ row ][ col ] ) = addr( arr ) + [ sizeof( int ) * COLS * row ]
Two dimensional arrays are stored in row major order, that is, row by row. Each row
contains COLS elements, which is why you see COLS in the formula. In fact, you
the number of rows. You just need to specify the number of columns. The reason is
the formula above. The compiler can compute the address of an element in a 2D
The compiler ignores ROWS. Thus, any 2D array with the COLS columns and any
Note that int **arr is an array of pointers (possibly to 1D arrays), while int arr[][
COLS ] is a 2D array. They are not the same type, and are not interchangeable.
Pointer Subtraction
It turns out you can subtract two pointers of the same type. The result is the
For example:
int arr[ 10 ] ;
int * p1 = arr + 2 ;
int * p2 = arr + 5 ;
117
cout << ( p2 - p1 ) ; // Prints 3
The formula used is rather simple. Assume that p1 and p2 are both pointers of
This can result in negative values if p2 has a smaller address than p1.
p2 and p1 need not point to valid elements in an array. The formula above still
Pointer subtraction isn't used very much, but can be handy to determine the
distances between two array elements (i.e., the difference in the array indexes).
You may not know exactly which element you're pointing to using pointer
In general, you can make a pointer point anywhere. For example, arr + 1000 is
valid, even if the array has only ten elements. arr - 1000 is also valid. That is, you
1000 ) core dumps because you are trying to access the address.
Here's an analogy. You can write down anyone's address on a piece of paper,
however, you can't just go inside the person's house at that address (which is like
118
dereferencing). Thus, computing addresses is fine, dereferencing it may cause
119