Escolar Documentos
Profissional Documentos
Cultura Documentos
by
Dr. Subodh Srivastava
Visiting faculty, CSE,IIT (BHU)
C - Pointers
Pointer Variables
The pointer data type
A data type for containing an address
rather than a data value
Integral, similar to int
Size is the number of bytes in which the
target computer stores a memory
address
Provides indirect access to values
CSC2110 - Data
Structures/Algorithms
Declaration of Pointer
Variables
A pointer variable is declared by:
dataType *pointerVarName;
The pointer variable pointerVarName is
used to point to a value of type
dataType
The * before the pointerVarName
indicates that this is a pointer variable,
not a regular variable
The * is not a part of the pointer variable
name
CSC2110 - Data
Structures/Algorithms
Pointer Variable
Declarations and Initialization
Pointer variables
Contain memory addresses as their values
Normal variables contain a specific value (direct
reference)
count
7
Pointer Variable
Declarations and Initialization
Pointer declarations
* used with pointer variables
int *myPtr;
#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var ); /* address
stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip ); /* access
the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it
produces result something as follows:
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
Pointer Operators
y
yPtr
500000
600000
y
600000
Address of
y is value
of yptr
Assignment of Pointer
Variables
A pointer variable has to be assigned a valid
memory address before it can be used in the
program
Example:
float data = 50.8;
float *ptr;
ptr = &data;
11
Assignment of Pointer
Variables (Cont ..)
FFF0
FFF1
FFF2
float *ptr;
FFF3
data
ptr = &data;
FFF4
50.8
FFF5
FFF6
CSC2110 - Data
Structures/Algorithms
12
Assignment of Pointer
Variables (Cont ..)
ptr
FFF0
FFF1
FFF2
float *ptr;
FFF3
data
ptr = &data;
FFF4
50.8
FFF5
FFF6
CSC2110 - Data
Structures/Algorithms
13
Assignment of Pointer
Variables (Cont ..)
ptr
FFF0
FFF4
FFF1
FFF2
float *ptr;
FFF3
data
ptr = &data;
FFF4
50.8
FFF5
FFF6
CSC2110 - Data
Structures/Algorithms
14
Assignment of Pointer
Variables (Cont ..)
Dont try to assign a specific integer value to a
pointer variable since it can be disastrous
float *ptr;
ptr = 120;
15
Initializing pointers
A pointer can be initialized during declaration
by assigning it the address of an existing
variable
float data = 50.8;
float *ptr = &data;
16
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.
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces
the following result:
The value of ptr is 0
C Pointers in Detail
Concept
Description
Concept
Description
C - Pointer arithmetic
C - Array of pointers
C - Pointer to pointer
Passing an argument by
reference or by address both
enable the passed argument
to be changed in the calling
function by the called
function.
ptr++
Now, after the above operation, the ptr will
point to the location 1004 because each
time ptr is incremented,
It will point to the next integer location
which is 4 bytes next to the current
location.
If ptr points to a character whose address
is 1000, then above operation will point to
the location 1001 because next
character will be available at 1001.
Incrementing a Pointer:
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr; /* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr ); /* move to the
next location */ ptr++;
}
return 0;
}
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {10, 100, 200};
int i, *ptr; /* let us have address of the first element in pointer
*/
ptr = var; i = 0; while ( ptr <= &var[MAX - 1] )
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr ); /* point to the
previous location */
ptr++;
i++;
}
return 0;
v[1]
v[2]
v[3]
v[4]
Calling Functions by
Reference
Call by reference with pointer arguments
Pass address of argument using & operator
Allows you to change actual location in memory
Arrays are not passed with & because the array
name is already a pointer
* operator
Program Output
2000 Prentice
const pointers
Outline
1. Declare variables
1.1 Declare const
pointer to an int
2. Change *ptr
(which is x)
2.1 Attempt to change
ptr
3. Output
Program Output
FIG07_13.c:
Error E2024 FIG07_13.c 16: Cannot modify a const
object in
function main
2000 Prentice
*** 1 errors in Compile ***
Psuedocode
Initialize array
print data in original order
Call function bubblesort
print sorted array
Define bubblesort
will print 40
3
ascending
order,
sorts
the values
into and prints the resulting
4 #include
array.
*/ <stdio.h>
5 #define SIZE 10
6 void bubbleSort( int *, const int );
7
8 int main()
9 {
10
11
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89,
12
int37
i;};
68, 45,
13
Bubblesort gets passed
14
printf( "Data items in
the original
address of array
15
order\n" );
elements (pointers). The
16
for ( i = 0; i < SIZE;
i++
) array is a
name
of an
17
printf( "%4d", a[ pointer.
i ] );
18
19
bubbleSort( a, SIZE );
/* sort
the
*/ "\nData items in ascending
20 array
printf(
21
order\n" );
22
for ( i = 0; i < SIZE; i++ )
23
printf( "%4d", a[ i ] );
24
25
printf( "\n" );
26
27
return 0;
28}
29
30void bubbleSort( int *array, const int size )
Outline
1. Initialize array
1.1 Declare variables
2. Print array
2.1 Call bubbleSort
2.2 Print array
2000 Prentice
33
int pass, j;
34
for ( pass = 0; pass < size - 1; pass++ )
35
36
for ( j = 0; j < size - 1; j++ )
37
38
if ( array[ j ] > array[ j + 1 ] )
39
swap( &array[ j ], &array[ j +
1 ] );
40}
41
42void swap( int *element1Ptr, int *element2Ptr
43{
)
44
int hold = *element1Ptr;
45
*element1Ptr = *element2Ptr;
46
*element2Ptr = hold;
47}
Data items in original order
2
6
4
8 10 12 89 68
Data items in ascending order
2
4
6
8 10 12 37 45
Outline
3. Function definitions
Program Output
45
37
2000 Prentice
7.9Arrays of Pointers
H e a r t s
suit[1]
D i a m o n \0
d s
suit[2]
C l u b s
suit[3]
S p a d e \0
s
\0
\0
0
1
2
3
deck[ 2 ][ 12 ] represents the King of
Clubs
King
Pseudocode
Top level:
First refinement:
Initialize the suit array
Initialize the face array
Initialize the deck array
Shuffle the deck
Deal 52 cards
Second refinement
Third refinement
2
Card shuffling dealing program */
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <time.h>
6
7 void shuffle( int [][ 13 ] );
8 void deal( const int [][ 13 ], const char
9
*[],
const char *[] );
10int main()
11{
12
const char *suit[ 4 ] =
13
{ "Hearts", "Diamonds", "Clubs",
"Spades"
}; char *face[ 13 ] =
14
const
15
{ "Ace", "Deuce", "Three", "Four",
16
"Five", "Six", "Seven", "Eight",
17
"Nine", "Ten", "Jack", "Queen",
18
int
"King"
}; deck[ 4 ][ 13 ] = { 0 };
19
20
srand( time( 0 ) );
21
22
shuffle( deck );
23
24
25
Outline
1. Initialize suit and
face arrays
1.1 Initialize deck
array
2. Call function
shuffle
2.1 Call function deal
3. Define functions
26}
27
28void shuffle( int wDeck[][ 13 ] )
29{
30
2000 Prentice
33
do {
Outline
The numbers 1-52 are
34
row = rand() % 4;
randomly placed into
35
column = rand() % 13;
3. Define functions
36
} while( wDeck[ row ][ column ] the
!= deck
0 );array.
37
38
wDeck[ row ][ column ] = card;
39
}
40}
41
42void deal( const int wDeck[][ 13 ], const
43
const char *wSuit[] )
char *wFace[],
44{
45
int card, row, column;
46
47
for ( card = 1; card <= 52; card++ )
48
Searches deck for
49
for ( row = 0; row <= 3; row++ ) the card number,
50
then prints the face
51
for ( column = 0; column <= 12;
and suit.
52
column++ )
53
if ( wDeck[ row ][ column ] ==
54
printf( "%5s of %-8s%c",
card )
55
wFace[ column ], wSuit[ row ],
56
card % 2 == 0 ? '\n' : '\t' );
57}
2000 Prentice
Outline
Six
Ace
Ace
Queen
Ten
Ten
Ten
Four
Six
Eight
Nine
Deuce
Five
Deuce
Five
King
Deuce
Ace
Three
Nine
Four
Eight
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
Clubs
Spades
Hearts
Clubs
Hearts
Spades
Diamonds
Diamonds
Diamonds
Hearts
Hearts
Spades
Clubs
Diamonds
Spades
Diamonds
Hearts
Clubs
Clubs
Clubs
Hearts
Diamonds
Seven
Ace
Queen
Seven
Deuce
Three
Four
Ten
Six
Three
Three
Six
Eight
Eight
King
Jack
Queen
King
King
Nine
Queen
Nine
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
of
Diamonds
Diamonds
Diamonds
Hearts
Clubs
Spades
Spades
Clubs
Spades
Diamonds
Hearts
Hearts
Clubs
Spades
Clubs
Spades
Hearts
Spades
Hearts
Spades
Spades
Diamonds
Program Output
2000 Prentice
Pointers to Functions
Pointer to function
Contains address of function
Similar to how array name is address of first
element
Function name is starting address of code that
defines function
Pointers to Functions
Example: bubblesort
Function bubble takes a function pointer
33
for ( counter = 0; counter < SIZE;
Outline
34
printf(
"%5d", a[ counter ] );
counter++
)
35
36
printf( "\n" );
3.1 Define functions
37
38
return 0;
39}
40
ascending and
41void bubble( int work[], const int size,descending return true
42
int (*compare)( int, int ) )
or false. bubble calls
43{
swap if the function call
44
int pass, count;
returns true.
45
46
void swap( int *, int * );
47
48
for ( pass = 1; pass < size; pass++ )
49
50
for ( count = 0; count < size - 1;
51
count++ )
52
if ( (*compare)( work[ count ],
53
swap(
&work[ count ],
Notice how function
work[ count + 1
] ) )
54}
&work[ count + 1 ] );
pointers are called using
55
the dereferencing
56void swap( int *element1Ptr, int *element2Ptr
operator. The * is not
57{
)
required, but
58
int temp;
emphasizes that
59
60
temp = *element1Ptr;
compare is a function
61
*element1Ptr = *element2Ptr;
pointer and not a
62
*element2Ptr = temp;
function.
2000 Prentice
63}
Program Output
Outline
in original order
4
8 10 12 89 68 45 37
in ascending order
6
12 37 order,
45 68 89
sort8in10
ascending
sort in descending order: 2
45
37
2000 Prentice
Outline
2000 Prentice