Вы находитесь на странице: 1из 105

Pointers

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.

What are pointers? Why should you care?


Pointers are aptly name: they "point" to locations in memory. Think of a row of safety deposit boxes of
various sizes at a local bank. Each safety deposit box will have a number associated with it so that you
can quickly look it up. These numbers are like the memory addresses of variables. A pointer in the world
of safety deposit box would simply be anything that stored the number of another safety deposit box.
Perhaps you have a rich uncle who stored valuables in his safety deposit box, but decided to put the real
location in another, smaller, safety deposit box that only stored a card with the number of the large box
with the real jewellery. The safety deposit box with the card would be storing the location of another box;
it would be equivalent to a pointer. In the computer, pointers are just variables that store memory
addresses, usually the addresses of other variables.

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.

A note about terms:


the word pointer : can refer either to a memory address itself, or
to a variable that stores a memory address. Usually, the
distinction isn't really that important: if you pass a pointer
variable into a function, you're passing the value stored in the
pointer--the memory address.
When I want to talk about a memory address, I'll refer to it as a
memory address;
when I want a variable that stores a memory address, I'll call it a
pointer.
When a variable stores the address of another variable, I'll say
that it is "pointing to" that variable. .

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;
}

What Are Pointers?


A pointer is a variable whose value is the address of
another variable, i.e., address of the memory location.
Like any variable or constant, you must declare a
pointer before you can use it to store any variable
address.

General Form : Pointer Variable


Declaration
The general form of a pointer variable declaration is:
<Variable_type> *var-name;
Here, variable_type is the pointer's base type; it must be a valid
C data type and var-name is the name of the pointer variable.
The asterisk * you used to declare a pointer is the same asterisk
that you use for multiplication.
However, in this statement the asterisk is being used to designate
a variable as a pointer.

Examples of valid pointer declaration:


int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

Pointer Variable Declarations and


Initialization
Pointer variables
Contain memory addresses as their values
Normal variables contain a specific value (direct
count
reference)
7

Pointers contain address of a variable that has a


specific value (indirect reference)
Indirection referencing a pointer value
countPtr

count
7

Pointer Variable Declarations and Initialization


Pointer declarations
* used with pointer variables

int *myPtr;
Declares a pointer to an int (pointer of type int *)
Multiple pointers require using a * before each variable declaration

int *myPtr1, *myPtr2;


Can declare pointers to any data type
Initialize pointers to 0, NULL, or an address
0 or NULL points to nothing (NULL preferred)

How to use Pointers?


Important operations:
(a) we define a pointer variable
(b) assign the address of a variable to a pointer and
(c) finally access the value at the address available in the
pointer variable.
This is done by using unary operator * that returns the
value of the variable located at the address specified by
its operand.

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;}

Example To Demonstrate Working of


Pointers

Example To Demonstrate Working of


Pointers

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.

Explanation of program and figure

Code c=11; makes the value of c, 11. Since, pointer pc is


pointing to address of c. Value of *pc will also be 11.
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.

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 */

How to store the address of a variable to another


variable?
int a;
int *b; // Declares a pointer to an int
b = &a; // address of a is stored in b
float a;
float *b; // Declares a pointer to a float
b = &a; // address of a is stored in b
char a;
char *b; // Declares a pointer to a char
b = &a; // address of a is stored in b

Sum of 2 numbers using pointers


#include <stdio.h>
int main()
{
int first=10, second=20, *p, *q, sum;
// printf("Enter two integers to add\n");
// scanf("%d%d", &first, &second);
p = &first; q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
return 0;}

Pointers and Arrays

C Programming Pointers and


Arrays
Arrays are closely related to pointers in C programming
but the important difference between them is that, a
pointer variable can take different addresses as value
whereas, in case of array it is fixed.

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.

Note: You may get different address of an array.

Relation between Arrays and


Pointers
Consider an array:
int arr[4];

Relation between Arrays and


Pointers
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.

Relation between Arrays and


Pointers
Hence, &arr[0] is equivalent to arr.
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.

Relation between Arrays and


Pointers
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1)
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2)
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3). . .

&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).

Program : To find sum on numbers


using array and pointers: Code 1

Program : To find sum on numbers


using array and pointers: Code 1
#include <stdio.h>
int main()
{
int array[5] = {5,4,3,6,1};
int *ptr, sum =0, i;
ptr = array;
for (i=0; i<5; i++)
{
sum = sum + *ptr;
ptr ++;
}
printf("sum is %d", sum);
return 0;
}

Program : To find sum on numbers


using array and pointers: Code 2

Program : To find sum on numbers


using array and pointers: Code 2
#include <stdio.h>
int main()
{
int array[5] = {5,4,3,6,1};
int sum =0, i;
for (i=0; i<5; i++)
{
sum += *(array+i);
}
printf("sum is %d", sum);
return 0;
}

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

Pointers and Functions - Call by


Reference

Pointers and Functions - Call by


Reference
When, argument is passed using pointer, address of the
memory location is passed instead of value.

Example of Pointer And Functions


Program to swap two number using call by
reference.

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.

Arrays as Function Arguments


void array_ input(int b[ ]);

Passing arrays to functions

Void modify(int b[]);


main( )
{
int a [5],k;
array_input(a);
for ( k=0; k<5; k++)
printf ( %d, a[ k ]);

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]);
}

void modify( int b[ ])


{
for ( k=0; k<5; k++)
{
b[ k ] = b[k]-5;
}}

Function returning pointers


int * fun()

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;

static 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.

Check This out !


X[0]

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

Such expressions are also allowed.

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:

Call By Value is Not Enough


Once the function parameters are initialized with copies
of the arguments, there is no further connection.
If the function changes its parameters, it affects the
local copy only.
To actually change the arguments in the caller, the
function needs access to the locations of the arguments,
not just their values.

Trace
move_one

x_ptr

y_ptr

void move_one ( int * x_ptr,


int * y_ptr )
{
*x_ptr = *x_ptr - 1;
*y_ptr = *y_ptr + 1;
}
a=4; b=7;
move_one( &a , &b ) ;

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

Function returning a pointer

Example: pointer and 1 D array


Write a program using pointers to compute the
sum of all elements stored in an array as well as
print the address of the elements.

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

Difference between %p and %x


Functions belonging to the printf function have the type
specifiers "%p" and "%x".

"x" and "X" serve to output a hexadecimal number.


"x" stands for lower case letters (abcdef) while "X" for
capital letters (ABCDEF).

"p" serves to output a pointer. It may differ depending


upon the compiler and platform.

Difference between %p and %x

int a = 10;
int *b = &a;
printf("%p\n",b);
printf("%X\n",b);

On a Win32 system, the following result will be printed:


0018FF20
18FF20

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().

ARRAY OF POINTERS 2D array


Pointers like any another data type can be grouped into
an array.
A one dimensional array of integer pointers can be
represented as :
int *x[10];
This declares an one dimensional array of ten integer
pointers, where each pointer in turn points to a integer
variable or an array.

int *x[10];

Now if we have a two dimensional array of integers


int array [10] [20] ;
And want pointer to point to each row of the array,
then we need to declare an array of 10 integer
pointer as follows:
int *x[10] ;
x[0]= array[0];
x[1] = array [1];
..

int array [10] [20]

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 )

array [1][5] is the element of 2nd row and 6th column .


( x+ 1 ) is the pointer to row 2.
As row 2 is one dimensional,
*(x+1) is actually the pointer to the first element in row 2.
If we add 5 to this pointer, that is ( *(x+1) + 5 ), it is a
pointer to element 6th in 2nd row .
*( *(x+1) + 5 ), refers to the element at column 6th row 2nd
which is array[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

Accessing Structure Members with


pointers
To access the members with structure variable, we
used (. dot) operator
But when we have a pointer of structure type , we use
arrow (->) to access the structure members.

Accessing Structure Members with


pointers

Example to access structure's member


through pointer.

Example to access structure's member


through pointer.
In this example, the pointer variable of type struct
name is referenced to the address of p.
Hence, only the structure member through pointer can
be accessed.
Structure pointer member can also be accessed using ->
operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b

Pointers & Strings

Pointer to array of string


A pointer which points to an array , whose content is
string, is known as pointer to array of strings.
Here
Ptr : It is pointer to array of string of size 4
Array[4]: it is an array and its content are string

Printing Address of character array

Printing contents of character array

Example
Write a pointer version of function strcpy( destination,source).

void string_cpy( char *, char * ) ;


int main( ){
char str1[20], str2 [20 ];
gets(str2);
string_cpy( str1, str2) ; //str1: destination, str2: source
}

void string_cpy( char *s, char * t )


{ int i;
for(i=0;*(t+i)!=\0;i++)
*( s + i) =*(t+i);
*(s+i)=\0; //Explicitly specify null character
for(i=0;*(s+i)!\0;i++)
printf(%c ,*(s+i));
}

Вам также может понравиться