Академический Документы
Профессиональный Документы
Культура Документы
C- Pointers
As we know, every variable is a memory location
And every memory location has its address defined
which can be accessed using ampersand (&) operator,
which denotes an address in memory.
The cool thing is that once you can talk about the address of a
variable, you'll then be able to go to that address and retrieve
the data stored in it.
If you happen to have a huge piece of data that you want to
pass into a function, it's a lot easier to pass its location to the
function than to copy every element of the data!
Moreover, if you need more memory for your program, you can
request more memory from the system--how do you get "back"
that memory? The system tells you where it is located in
memory; that is to say, you get a memory address back. And
you need pointers to store the memory address.
Example:
Consider the following example, which will print the
address of the variables defined:
#include <stdio.h>
int main()
{
int var1;
char var2[10];
printf(Address of variable 1: %x\n", &var1);
printf(Address of variable 2: %x\n", &var2);
return 0;
}
count
7
int *myPtr;
Declares a pointer to an int (pointer of type int *)
Multiple pointers require using a * before each variable declaration
Example
#include <stdio.h>
int main()
{
int var1 =20;
int *ptr;
ptr= &var1;
printf("Address of variable 1: %x\n", &var1);
/* address stored in ptr variable*/
printf("Address stored in ptr variable 2: %x\n", ptr);
/* Access the value using the pointer */
printf("Value stored in *ptr variable: %d\n", *ptr);
return 0;}
Explanation
Code int *pc, c; creates a pointer pc and a variable c. Pointer pc points to some
address and that address has garbage value. Similarly, variable c also has garbage
value at this point.
Code c=22; makes the value of c equal to 22, i.e.,22 is stored in the memory
location of variable c.
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 (value of pointer pc) will be
equal to the value of c.
Advantages of Pointers
Pointers provide direct access to memory
Pointers provide a way to return more than one value to
the functions
Reduces the storage space and complexity of the program
Reduces the execution time of the program
Provides an alternate way to access array elements
Pointers can be used to pass information back and forth
between the calling function and called function.
Advantages of Pointers
Pointers allows us to perform dynamic memory
allocation and deallocation.
Pointers helps us to build complex data structures like
linked list, stack, queues, trees, graphs etc.
Pointers allows us to resize the dynamically allocated
memory block.
Addresses of objects can be extracted using pointers
Disadvantages of Pointers
Uninitialized pointers might cause segmentation fault.
Dynamically allocated block needs to be freed
explicitly. Otherwise, it would lead to memory leak.
Pointers are slower than normal variables.
If pointers are updated with incorrect values, it might
lead to memory corruption.
NULL Pointers in C
It is always a good practice to assign a NULL value to a
pointer variable in case you do not have exact address to
be assigned.
This is done at the time of variable declaration.
A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero
defined in several standard libraries.
Example
Explanation
On most of the operating systems, programs are not
permitted to access memory at address 0 because that
memory is reserved by the operating system.
Commonly, the null pointer is used to denote the end of
a memory search or processing event.
In computer programming, a null pointer is a pointer
that does not point to any object or function.
Explanation
But by convention, if a pointer contains the null (zero)
value, it is assumed to point to nothing.
To check for a null pointer you can use an if statement
as follows:
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Example
#include <stdio.h>
int main()
{
char c[4];
int i;
for(i=0; i<4; i++)
{
printf("Address of c[%d] = %x \n", i, &c[i]);
}
return 0;
}
Important Note
Notice, that there is equal difference (difference of 1
byte) between any two consecutive elements of array.
Exercise
1) Write a C program to find the largest in an array using
pointers.
2) Write a C program to calculate the average using array
and pointers
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.
void array_input(int b[ ] )
{
for ( k=0; k<5; k++)
{
scanf ( %d, &b[ k ])
}}
modify(int a);
for(k=0;k<5;k++)
Printf(%d,a[k]);
}
int * fun()
main(){
main(){
int *p;
int *p;
p=fun();
p=fun();
printf(%d,p);
printf(%d,p);
printf(%d,*p); }
printf(%d,*p); }
int *fun()
int *fun()
int i=20;
Return(&i); }
Return(&i); }
Operation On Pointers
One can add or subtract an integer to or from a pointer
variable:
p1 = p1 + 12 ;
above expression will make p1 to point to 12 th element of
p1 type beyond the one it is currently pointing to.
Multiplication and Division operations can not be applied
to pointer variables:
p1 = p1 * 12 ; ERROR: invalid use of pointers.
Important
Beside addition and subtraction of a pointer and an
integer, only one other operation is allowed:
One can subtract one pointer from another in order to
find the number of objects of base type that separate the
two.
Example:
If P1 and P2 are two pointer variables then P2- P1 gives
the number of elements between P1 and P2
All other arithmetic operations are PROHIBITED.
x[1]
1
1000
x[2]
x[3]
2
1002
1004
1006
*p1
x[4]
5
1008
*p2
p2- p1 = ????
DONTS
One can not add two pointer variables : p1 + p2 ;
One can not multiply or divide pointer variables:
P1 * P2 is illegal.
P1 *12 or P1 / 3 is illegal.
One can not add or subtract float or double value to or
from a pointer.
Pointer expression
If p1 and p2 are two integer pointers :
Y = ( * p1) * ( * p2) ;
sum = sum + * p1;
Z = 5 * - *p2 /
*p1 ;
*p2 = *p2 + 10;
Sum + = *p2;
P1 ++;
Example
int main( ){
int a, b, *p1, *p2, x,y,z;
a=12; b=4;
p1=&a;
p2=&b;
x = (*p1 ) * (*p2) 6 ;
y = 4 * - (*p1 ) / (* p2) + 10 ;
printf( x = %d, y =%d, x, y );
*p2 = *p2 + 3 ;
*p1 = * p2 - 5 ;
z = *p1 + *p2 - 6 ;
printf ( z = %d , z );
}
Output:
x = 42,
Z=8
y = -2
Comparison
In addition to arithmetic operations, pointers can also be
compared using the relational operators:
P1 > P2
P1 == P2
P1 != P2
Trace
move_one
X
4 3
7 8
X
/* change x and y */
void move_one ( int x, int y )
{
x = x - 1;
y = y + 1;
}
void main ( void ) {
int a, b ;
a=4; b=7;
move_one(a, b) ;
printf(%d %d, a ,b);
}
Trace
move_one
X
4 3
7 8
X
main
/* change x and y */
void move_one ( int x, int y )
{
x = x - 1;
y = y + 1;
}
void main ( void ) {
int a, b ;
a=4; b=7;
move_one(a, b) ;
printf(%d %d, a ,b);
}
Output:
Trace
move_one
x_ptr
y_ptr
main
X
4 3
7 8
X
Output:
Trace
void move_one (
int * x_ptr,
int * y_ptr ) {
*x_ptr = *x_ptr - 1;
*y_ptr = *y_ptr + 1;
}
main
X
4 3
7 8
X
a=4; b=7;
move_one( &a , &b ) ;
Output:
3 8
Solution
int main(void){
int *p, sum=0,m=0;
int x[5]= { 5,9,6,3,7};
p=x;
// initializes pointer p to points to the array x first element
printf( \nelement
value
address\n);
while(m<5) {
printf( x[%d]
%d
%p\n, m, *p, p);
sum = sum + *p;
m++; p++; }
printf( \n SUM : %d, sum);
printf(\n &x[0] = %p, &x[0]); // Address of first element
printf(\n p = %p, p);// Serves to output a pointer
}
output
Element
X[0]
X[1]
X[2]
X[3]
X[4]
value
5
9
6
3
7
SUM = 30
&X[0] = FE1A
p = FE25
address
FE1A
FE1C
FE1E
FE21
FE23
int a = 10;
int *b = &a;
printf("%p\n",b);
printf("%X\n",b);
Important
In case of a single dimensional array,
elements can be accessed either as x[ i ] where 0<= i <
size of array or
if we have a pointer to the array, elements can be
accessed as *( p + i ) where 0<= i < size of array.
Exercise
In the main function store the scores taken by a player
for 100 matches inside an array . Write a function that
reads the content of this array using pointer as a
parameter, counts and displays the total centuries made
by him in his career of 100 matches.
Write a function int string_length(char * ) that computes
and returns the length of string passed to it. Simulation
of library function strlen().
int *x[10];
int *x[10]
1
2
3
4
X+1
X+2
X+3
X+4
X+5
X+6
*(*(x+1) + 0 )
*(*(x+1) + 5 )
int array[3][3];
int *x[3];
int i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{ array[i][j]=i+j;
printf("\narray[%d][%d]=%d",i,j,array[i][j]);
}
for(i=0;i<3;i++)
{ x[i]=array[i] ;
printf("\n\n x[%d]=%x,array[%d]=%p",i,*(x+i),i, array[i]);
}
printf("\n%d",*(*(x+1)+2) );
// accessing x[1][2] element;
printf("\narray[1][2]=%d", array[1][2]);
Output:
array[0][0]=0
X[0]=fdee
array[0]=FDEE
array[0][1]=1
X[1]=fdf4
array[1]=FDF4
array[0][2]=2
X[2]=fdfa
array[2]=FDFA
array[1][0]=1
array[1][1]=2
Array[1][2]=3
array[1][2]=3
array[2][0]=2
array[2][1]=3
array[2][2]=0
Pointer to Structure
Pointer to Structure
Like we have array of integers , array of pointers etc, we
can also have array of structure variables.
To make use of array of structure variables efficient, we
use pointers of structure type.
We can also have pointer to a single structure variable,
but it is mostly used with array of structure variables.
Pointer to structure
Pointer to structure
Example
Write a pointer version of function strcpy( destination,source).