Pointers 1
Pointers
1
Outline
n Computer Memory Structuren Addressing Conceptn Introduction to Pointern Pointer Manipulationn Summary
2
Computer Memory Revisited
n Computers store data in memory slotsn Each slot has an unique addressn Variables store their values like this:
Addr Content Addr Content Addr Content Addr Content1000 i: 37 1001 j: 46 1002 k: 58 1003 m: 741004 a[0]: ‘a’ 1005 a[1]: ‘b’ 1006 a[2]: ‘c’ 1007 a[3]: ‘\0’1008 ptr: 1001 1009 … 1010 1011
3
Computer Memory Revisited
n Altering the value of a variable is indeed changing the content of the memoryn e.g. i = 40; a[2] = ‘z’;
Addr Content Addr Content Addr Content Addr Content1000 i: 40 1001 j: 46 1002 k: 58 1003 m: 741004 a[0]: ‘a’ 1005 a[1]: ‘b’ 1006 a[2]: ‘z’ 1007 a[3]: ‘\0’1008 ptr: 1001 1009 … 1010 1011
4
Addressing Concept
n Pointer stores the address of another entity
n It refers to a memory locationint i = 5;
int *ptr; /* declare a pointer variable */
ptr = &i; /* store address-of i to ptr */
printf(“*ptr = %d\n”, *ptr); /* refer to referee of ptr */
5
Why do we need Pointer?
n Pointers are more efficient in handling arrays and stringsn Can be used to return multiple values from a functionn Allows dynamic memory allocationn Reduces length and complexity of the programn Increases execution speed and thus reduces program
execution time
Remember this?
scanf(“%d”, &i);
6
What actually ptr is?
n ptr is a variable storing an addressn ptr is NOT for storing the actual value of i
int i = 5;
int *ptr;
ptr = &i;
printf(“i = %d\n”, i);
printf(“*ptr = %d\n”, *ptr);
printf(“ptr = %p\n”, ptr);
5i
address of iptr
Output:i = 5
*ptr = 5
ptr = effff5e0
value of ptr = address of iin memory
7
Twin Operators
n &: Address-of operatorn Get the address of an entity
n e.g. ptr = &j;
Addr Content Addr Content Addr Content Addr Content1000 i: 40 1001 j: 33 1002 k: 58 1003 m: 741004 ptr: 1001 1005 1006 1007
8
Twin Operators
n *: De-reference operatorn Refer to the content of the referee
n e.g. *ptr = 99;
Addr Content Addr Content Addr Content Addr Content1000 i: 40 1001 j: 99 1002 k: 58 1003 m: 741004 ptr: 1001 1005 1006 1007
9
Example: Pass by Reference
n Modify behaviour in argument passingvoid f(int j)
{
j = 5;
}
void g()
{
int i = 3;
f(i);
}
void f(int *ptr)
{
*ptr = 5;
}
void g()
{
int i = 3;
f(&i);
} i = ?i = ?i = 3 i = 5
10
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 5j int integer variable 10
11
An Illustrationint i = 5, j = 10;
int *ptr; /* declare a pointer-to-integer variable */
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 5j int integer variable 10
ptr int * integer pointer variable
12
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr; /* declare a pointer-to-pointer-to-integer variable */
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 5j int integer variable 10
ptr int * integer pointer variablepptr int ** integer pointer pointer variable
Double Indirection
13
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i; /* store address-of i to ptr */
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 5j int integer variable 10
ptr int * integer pointer variable address of ipptr int ** integer pointer pointer variable*ptr int de-reference of ptr 5
14
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr; /* store address-of ptr to pptr */
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 5j int integer variable 10
ptr int * integer pointer variable address of ipptr int ** integer pointer pointer variable address of ptr*pptr int * de-reference of pptr value of ptr
(address of i) 15
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 3j int integer variable 10
ptr int * integer pointer variable address of ipptr int ** integer pointer pointer variable address of ptr*ptr int de-reference of ptr 3
16
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 7j int integer variable 10
ptr int * integer pointer variable address of ipptr int ** integer pointer pointer variable address of ptr
**pptr int de-reference of de-reference of pptr
717
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 7j int integer variable 10
ptr int * integer pointer variable address of jpptr int ** integer pointer pointer variable address of ptr*ptr int de-reference of ptr 10
18
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 7j int integer variable 9
ptr int * integer pointer variable address of jpptr int ** integer pointer pointer variable address of ptr
**pptr int de-reference of de-reference of pptr
919
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable 7j int integer variable 9
ptr int * integer pointer variable address of ipptr int ** integer pointer pointer variable address of ptr*pptr int * de-reference of pptr value of ptr
(address of i) 20
An Illustrationint i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3;
**pptr = 7;
ptr = &j;
**pptr = 9;
*pptr = &i;
*ptr = -2;
Data TableName Type Description Value
i int integer variable -2j int integer variable 9
ptr int * integer pointer variable address of ipptr int ** integer pointer pointer variable address of ptr*ptr int de-reference of ptr -2
21
Pointer Arithmetic
n What’s ptr + 1? èThe next memory location!n What’s ptr - 1? èThe previous memory location!n What’s ptr * 2 and ptr / 2?èInvalid operations!!!
22
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) ?a[1] float float array element (variable) ?a[2] float float array element (variable) ?a[3] float float array element (variable) ?ptr float * float pointer variable*ptr float de-reference of float pointer
variable?
23
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) ?a[1] float float array element (variable) ?a[2] float float array element (variable) ?a[3] float float array element (variable) ?ptr float * float pointer variable address of a[2]*ptr float de-reference of float pointer
variable?
24
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) ?a[1] float float array element (variable) ?a[2] float float array element (variable) 3.14a[3] float float array element (variable) ?ptr float * float pointer variable address of a[2]*ptr float de-reference of float pointer
variable3.14
25
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) ?a[1] float float array element (variable) ?a[2] float float array element (variable) 3.14a[3] float float array element (variable) ?ptr float * float pointer variable address of a[3]*ptr float de-reference of float pointer
variable?
26
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) ?a[1] float float array element (variable) ?a[2] float float array element (variable) 3.14a[3] float float array element (variable) 9.0ptr float * float pointer variable address of a[3]*ptr float de-reference of float pointer
variable9.0
27
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) ?a[1] float float array element (variable) ?a[2] float float array element (variable) 3.14a[3] float float array element (variable) 9.0ptr float * float pointer variable address of a[0]*ptr float de-reference of float pointer
variable?
28
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) 6.0a[1] float float array element (variable) ?a[2] float float array element (variable) 3.14a[3] float float array element (variable) 9.0ptr float * float pointer variable address of a[0]*ptr float de-reference of float pointer
variable6.0
29
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) 6.0a[1] float float array element (variable) ?a[2] float float array element (variable) 3.14a[3] float float array element (variable) 9.0ptr float * float pointer variable address of a[2]*ptr float de-reference of float pointer
variable3.14
30
Pointer Arithmetic and Arrayfloat a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
Data TableName Type Description Valuea[0] float float array element (variable) 6.0a[1] float float array element (variable) ?a[2] float float array element (variable) 7.0a[3] float float array element (variable) 9.0ptr float * float pointer variable address of a[2]*ptr float de-reference of float pointer
variable7.0
31
Pointer Arithmetic and Array
n Type of a is float *n a[2] è *(a + 2)
ptr = &(a[2])è ptr = &(*(a + 2))
è ptr = a + 2
n a is a memory address constantn ptr is a pointer variable
float a[4];
float *ptr;
ptr = &(a[2]);
*ptr = 3.14;
ptr++;
*ptr = 9.0;
ptr = ptr - 3;
*ptr = 6.0;
ptr += 2;
*ptr = 7.0;
32
More Pointer Arithmetic
n What if a is a double array?n A double may occupy more memory slots!
n Given double *ptr = a;n What’s ptr + 1 then?
Addr Content Addr Content Addr Content Addr Content1000 a[0]: 37.9 1001 … 1002 … 1003 …1004 a[1]: 1.23 1005 … 1006 … 1007 …1008 a[2]: 3.14 1009 … 1010 … 1011 …
33
More Pointer Arithmetic
n Arithmetic operators + and – auto-adjust the address offset. Also called as scale factor
n According to the type of the pointer:n 1000 + sizeof(double) = 1000 + 4 = 1004
Addr Content Addr Content Addr Content Addr Content1000 a[0]: 37.9 1001 … 1002 … 1003 …1004 a[1]: 1.23 1005 … 1006 … 1007 …1008 a[2]: 3.14 1009 … 1010 … 1011 …
34
1.Declare variables
2 Initialize variables
3. Print
Program Output
1 /* 2 Using the & and * operators */3 #include <stdio.h>45 int main()6 {7 int a; /* a is an integer */8 int *aPtr; /* aPtr is a pointer to an integer */910 a = 7;11 aPtr = &a; /* aPtr set to address of a */1213 printf( "The address of a is %p" 14 "\nThe value of aPtr is %p", &a, aPtr );1516 printf( "\n\nThe value of a is %d" 17 "\nThe value of *aPtr is %d", a, *aPtr );1819 printf( "\n\nShowing that * and & are inverses of "20 "each other.\n&*aPtr = %p" 21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr );2223 return 0;24 }The address of a is 0012FF88The value of aPtr is 0012FF88 The value of a is 7The value of *aPtr is 7Proving that * and & are complements of each other.&*aPtr = 0012FF88*&aPtr = 0012FF88
The address of a is the value of aPtr.
The * operator returns an alias to what its operand points to. aPtr points to a, so *aPtr returns a.
Notice how * and & are inverses
Calling Functions by Reference
n Call by reference with pointer argumentsn Pass address of argument using & operatorn Allows you to change actual location in memoryn Arrays are not passed with & because the array name is
already a pointern * operator
n Used as alias/nickname for variable inside of functionvoid double( int *number ) {
*number = 2 * ( *number ); }
n *number used as nickname for the variable passed
1.Function prototype
1.1 Initialize variables
2. Call function
3. Define function
Program Output
1 /* 2 Cube a variable using call-by-reference 3 with a pointer argument */4
5 #include <stdio.h>5 #include <stdio.h>66
7 void cubeByReference( int * ); /* prototype */7 void cubeByReference( int * ); /* prototype */88
9 int main()9 int main()10 {10 {
11 int number = 5;11 int number = 5;1213 printf( "The original value of number is %d", number );13 printf( "The original value of number is %d", number );14 cubeByReference( &number );15 printf( "\nThe new value of number is %d\n", number );1617 return 0;18 }1920 void cubeByReference( int *nPtr )21 {22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */23 }
The original value of number is 5The new value of number is 125
Notice how the address of number is given - cubeByReference expects
a pointer (an address of a variable).
Inside cubeByReference, *nPtr is used (*nPtr is number).
Notice that the function prototype takes a pointer to an integer (int *).
Bubble Sort Using Call-by-reference
n sizeof
n Returns size of operand in bytesn For arrays: size of 1 element * number of elementsn if sizeof( int ) equals 4 bytes, then
int myArray[ 10 ];printf( "%d", sizeof( myArray ) );
n will print 40
n sizeof can be used withn Variable namesn Type namen Constant values
1. Initialize array
1.1 Declare variables
2. Print array
2.1 Call bubbleSort
2.2 Print array
1 /* 2 This program puts values into an array, sorts the values into3 ascending order, and prints the resulting array. */4 #include <stdio.h>5 #define SIZE 106 void bubbleSort( int *, const int );78 int main()9 {10 11 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };12 int i;1314 printf( "Data items in original order\n" );1516 for ( i = 0; i < SIZE; i++ )17 printf( "%4d", a[ i ] );1819 bubbleSort( a, SIZE ); /* sort the array */20 printf( "\nData items in ascending order\n" );2122 for ( i = 0; i < SIZE; i++ )23 printf( "%4d", a[ i ] ); 2425 printf( "\n" );2627 return 0;28 }2930 void bubbleSort( int *array, const int size )31 {32 void swap( int *, int * );
Bubblesort gets the address of array elements (pointers).
The name of an array is a pointer.
3. Function definitions
Program Output
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
42 void 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 45 37Data items in ascending order 2 4 6 8 10 12 37 45
Pointers to 2-D array
n Assume int a[3][4]
41
Pointers to 2-D arrayn Assume int a[3][4]n A 2-D array is stored in contiguous memory location in row
majorn So 1st element of 2nd row is actually base address + row_number * no of elements in each rown In general a[i][j] is eq to *(p + row_count * i + j)n eg. a[2][3] is given by *(p+2*4+3) = *(p+11)n Hence when a 2-D array is declared using pointer, we need
size of row n int (*p)[4]n Here p is defined to be a pointer to a group of contiguous, one-dimensional, 4-element
integer arrays. 42
Pointers to 2-D arrayn Since p was defined to be a pointer to a group of
contiguous, one-dimensional, 4-element integer arrays.
n p+1 points to next 1-D array (row # 1)n *(p+i) points to first element in the ith rown *(p+i) + j - points to jth element on ith rown *(*(p+i) + j) - Value stored in cell(i,j)
43
Pointers and Strings
n Strings are treated like character arraysn They are declared as
char str[5]=”Good”n Compiler automatically inserts the null character at the
end of stringn Strings can be created using pointersn char *str = “Good”n It creates a string for the literal and then stores its
address in pointer variable str
str 44
G o o d \0.
String handling by pointers
Pointer to structure variables
Advice and Precaution
n Prosn Efficiencyn Convenience
n Consn Error-pronen Difficult to debug
47
Summary
n A pointer stores the address (memory location) of another entity
n Address-of operator (&) gets the address of an entity
n De-reference operator (*) makes a reference to the referee of a pointer
n Pointer and arrayn Pointer arithmetic
48