You are on page 1of 25

POINTERS

EKT 120:Computer Programming


Outline
 Introduction
 Pointer Variable Definitions and Initialization
 Pointer Operators
 Calling Functions by Reference
 Using the const Qualifier with Pointers
 Pointer Expressions and Pointer Arithmetic
 Relationship between Pointers and Arrays
 Arrays of Pointers

EKT 120:Computer Programming


Introduction
 Pointer is the address (i.e. a specific memory
location) of an object.
 It can refer to different objects at different times.
 Pointers are used in C programs for a variety of
purposes:
 To return more than one value from a function(using pass
by reference)
 To create and process strings
 To manipulate the contents of arrays and structures
 To construct data structures whose size can grow or shrink
dynamically

EKT 120:Computer Programming


Pointer Variable Definitions and
Initialization
 Pointer variables
 Contain memory addresses as their values
 Normal variables contain a specific value (direct
reference) iNum
7

 Pointer contains an address of a variable that has


a specific value (indirect reference)
 Indirection – referencing a pointer value
piNum iNum
7

EKT 120:Computer Programming


Pointer Variable Definitions and
Initialization
 Pointer definitions
 * used with pointer variables
int *piNum;
 Defines a pointer to an int (pointer of type int *)
 Multiple pointers require using a * before each variable
definition
int *piNum1, *piNum2;
 Can define pointers to any data type
 Initialize pointers to 0, NULL, or an address
 0 or NULL – points to nothing (NULL preferred)
 int *piNum = NULL; or int *piNum = 0;
EKT 120:Computer Programming
Pointer Operators
 Symbol & is called address operator
 Returns address of operand
int iNum = 7;
int *piNum;
piNum = &iNum; /* piNum gets address of iNum */
/* piNum “points to” iNum */

iNum piNum iNum


7 500000 600000 600000 7
piNum

Address of
iNum is value
of piNum
EKT 120:Computer Programming
Similar pointer operation

#include <stdio.h> #include <stdio.h> Output


int main( ) int main( ) 15
{ int value1 = 10; { int value1 = 10;
int *vPtr; int *vPtr = &value1;
value1 += 5;
vPtr = &value1;
value1 += 5; printf("%d\n", *vPtr);
return 0;
printf("%d\n", *vPtr); }
return 0;
}

UniMAP SemII-09/10 EKT 120:Computer Programming


Pointer Operators
 Symbol * is called indirection/dereferencing
operator
 Returns a synonym/alias of what its operand points to
 *piNum returns iNum (because piNum points to iNum)
 * can also be used for assignment
 Returns alias to an object

*piNum = 10; /* changes iNum to 10 */ show pictures!!


 Dereferenced pointer (operand of *) must be an lvalue (no
constants)
 * and & are inverses
 They cancel each other out

EKT 120:Computer Programming


Sample program
number = 7
piNum points to iNum whereby the value is = 7
#include <stdio.h> Address of piNum : 1245060 Contents of piNum : 1245064
int main() Address of iNum : 1245064
{ int iNum;
int *piNum; Dereferencing pointer, *piNum = 15
int iNum1=5; iNum = 20
*piNum = 20
iNum = 7; *piNum + iNum1 = 25
printf("number = %d\n", iNum);
piNum = &iNum;
printf(“piNum points to iNum whereby the value is = %d\n",*piNum);
printf("Address of piNum : %d Contents of piNum : %d\n", &piNum, piNum);
printf("Address of iNum : %d\n\n", &iNum);

*piNum = 15;
printf("Dereferencing pointer, *piNum = %d\n", *piNum);
iNum = iNum + iNum1;
printf(“iNum = %d\n”, iNum);
printf("*piNum = %d\n", *piNum);
printf("*piNum + iNum1 = %d\n", *piNum + iNum1);
return 0;
}
EKT 120:Computer Programming
Calling Functions by Reference
 Call by reference with pointer arguments
 Passes 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
 Used as alias or nickname for variable inside of function
void fnFun1 (int *piNumber)
{
*piNumber = 2 * (*piNumber);
}
 *piNumber used as nickname for the variable passed

EKT 120:Computer Programming


Enter character : f

Remember..last time
Do you want to continue?y
Enter character : I
Do you want to continue?y
#include <stdio.h> Enter character : k
#include <string.h> Do you want to continue?n
char fnRead(); Number of vowel : 1
void fnFindCountVC(char, int*, int*); Number of consonant : 2
void fnPrint(int,int);
void fnFindCountVC(char cCh1, int *piVowel, int
int main() *piConsonant)
{ char cCh, cChoice; int iCountV=0, iCountC=0; {
do switch(cCh1)
Functions that “return”
{ cCh = fnRead(); { case 'A':
more than one value i.e.
fnFindCountVC(cCh, &iCountV, &iCountC); case 'a':
arguments are passed by
printf("Do you want to continue? "); case 'E':
reference
scanf("%c", &cChoice); case 'e':
getchar(); case 'I':
}while((cChoice == 'y') ||(cChoice =='Y')); case 'i':
fnPrint(iCountV,iCountC); case 'O':
return 0; case 'o':
} case 'U':
case 'u': *piVowel = *piVowel +1;break;
char fnRead() default: *piConsonant = *piConsonant + 1;
{ char cCh1; }
printf("Enter character : "); }
scanf("%c", &cCh1); void fnPrint(int iVowel, int iConsonant)
getchar(); {
return(cCh1); printf("Number of vowel : %d\n", iVowel);
} printf("Number of consonant : %d\n", iConsonant);
} 11
Remember…last time
int main()
{
#include <stdio.h>
int aiListA [iArraySize] = {0};
int aiListB [iArraySize];
const int iArraySize = 10;
void fnInitializeArray (int aiX[], int iSizeX);
fnPrintArray (aiListA, iArraySize);
void fnFillArray (int aiX[], int iSizeX);
fnInitializeArray (aiListB, iArraySize);
void fnPrintArray (const int aiX[], int iSizeX);
fnPrintArray (aiListB, iArraySize);
int fnSumArray (const int aiX[], int iSizeX);
fnFillArray (aiListA, iArraySize);
int fnIndexLargestElement (const int aiX[], int iSizeX);
fnPrintArray (aiListA, iArraySize);
void fnCopyArray (const int aiX[], int aiY[], int iLength);
fnSumArray (aiListA, iArraySize);
fnCopyArray (aiListA, aiListB, iArraySize);
void fnInitializeArray (int aiX[ ], int iSizeX) fnPrintArray (aiListB, iArraySize);
{ return 0;
int iCounter; }

for (iCounter = 0; iCounter < iSizeX; iCounter++)


aiX[iCounter] = 0;
}

EKT 120:Computer Programming


Using the const Qualifier
with Pointers
 const qualifier
 Variable cannot be changed
 Use const if function does not need to change a variable
 Attempting to change a const variable produces an error
 const pointers
 Point to a constant memory location
 Must be initialized when defined
 int *const piMyPtr = &iX;
 Type int *const – constant pointer to an int

 const int *piMyPtr = &iX;


 Regular pointer to a const int

 const int *const piPtr = &iX;


 const pointer to a const int

 iX can be changed, but not *piPtr

EKT 120:Computer Programming


Pointer Expressions and
Pointer Arithmetic
 Arithmetic operations can be performed on
pointers
 Increment/decrement pointer (++ or --)
 Add an integer to a pointer( + or += , - or -=)
 Pointers may be subtracted from each other
 Operations meaningless unless performed on an
array

EKT 120:Computer Programming


Pointer Expressions and
Pointer Arithmetic
 5 element int array on machine with 4 byte ints
 piVPtr points to first element aiV[ 0 ]
 at location 3000 (piVPtr = 3000)

 piVPtr += 2; sets piVPtr to 3008


 piVPtr points to aiV[ 2 ] (incremented by 2), but the

machine has 4 byte ints, so it points to address 3008


location
3000 3004 3008 3012 3016

aiV[0] aiV[1] aiV[2] aiV[3] aiV[4]

pointer variable piVPtr


EKT 120:Computer Programming
Pointer Expressions and
Pointer Arithmetic
 Subtracting pointers
 Returns number of elements from one to the
other. If
piVPtr2 = &aiV[ 2 ];
piVPtr = &aiV[ 0 ];
 piVPtr2 - piVPtr would produce 2

 Pointer comparison ( <, == , > )


 See which pointer points to the higher numbered
array element
 Also, see if a pointer points to 0

EKT 120:Computer Programming


Pointer Expressions and
Pointer Arithmetic
 Pointers of the same type can be assigned to
each other
 If not the same type, a cast operator must be
used
 Exception: pointer to void (type void *)
 Generic pointer, represents any type
 No casting needed to convert a pointer to void pointer
 void pointers cannot be dereferenced

EKT 120:Computer Programming


Example of Pointer Operation
#include <stdio.h> Address of piVPtr : 1245064 Contents of piVPtr : 1245020
int main() Address of aiV[0] : 1245020
{int *piVPtr; int *piVPtr2; Address of piVPtr + 2: 1245028
int aiV[5] = {10,20,30,40,50}; int iTemp; Address of piVPtr + 4: 1245036
int *piP, *piQ; Contents of temp : 2
Contents of piP : 2147323904 piQ : 2147323904
piVPtr= aiV;
printf("Address of piVPtr : %d Contents of piVPtr :
%d\n", &piVPtr, piVPtr);
printf("Address of aiV[0] : %d\n", &aiV);
piVPtr +=2;
printf("Address of piVPtr + 2: %d\n", piVPtr);
piVPtr +=2;
printf("Address of piVPtr + 4: %d\n", piVPtr);

piVPtr2=&aiV[2];
piVPtr=&aiV[0];
iTemp=piVPtr2-piVPtr;
printf("Contents of iTemp : %d\n", iTemp);

piP=piQ;
printf("Contents of piP : %d piQ : %d\n", piP, piQ);
return 0;}
UniMAP SemII-09/10 EKT 120:Computer Programming
The Relationship between
Pointers and Arrays
 Arrays and pointers are closely related
 Array name like a constant pointer
 Pointers can do array subscripting operations
 Define an array aiB[5] and a pointer piBPtr
 To set them equal to one another use:
piBPtr = aiB;
 The array name (aiB) is actually the address of first
element of the array aiB[ 5 ]
piBPtr = &aiB[0];
 Explicitly assigns piBPtr to the address of first element of
aiB

EKT 120:Computer Programming


The Relationship between
Pointers and Arrays
 Element aiB[3]
 Can be accessed by *(piBPtr + 3)
 Where * is the offset. Called pointer/offset notation
 Can be accessed by piBPtr[3]
 Called pointer/subscript notation
 piBPtr[3] same as aiB[3]
 Can be accessed by performing pointer
arithmetic on the array itself
*(aiB + 3)

EKT 120:Computer Programming


Example 1
//array and pointer style Output:
#include <stdio.h>
int main() for(i=0;i<3;i++) 10
{int *piVPtr, i; printf("%d\n", *(aiV + i)); 20
int aiV[3] = {10,20,30}; printf("\n");
30
//pointer but array style
piVPtr= aiV; 10
//standard array processing for(i=0;i<3;i++)
20
for(i=0;i<3;i++) printf("%d\n", piVPtr[i]);
30
printf("%d\n", aiV[i]); printf("\n");
printf("\n"); return 0; 10
} 20
//pointer style
for(i=0;i<3;i++) 30
printf("%d\n", *(piVPtr + i));
printf("\n"); 10
20
30
UniMAP SemII-09/10 EKT 120:Computer Programming
Address of piBPtr : 1245064 Contents of piBPtr : 1245016
Address of aiB : 1245016 Contents of aiB[0]:10 10 10
piBPtr points to aiB[0] = 10

I am accessing element aiB[3]!!

Example 2
Let see how many ways I can do it
aiB[3] = 40
*(piBPtr + 3) = 40
*(aiB + 3) = 40
piBPtr[3] = 40

aiB[0] = 10
aiB[1] = 20
aiB[2] = 30
aiB[3] = 40
aiB[4] = 50
aiB[5] = 0
#include <stdio.h> aiB[6] = 0
int main() aiB[7] = 0
{ int *piBPtr ;int iIndex; aiB[8] = 0
aiB[9] = 0
int aiB[10]={10,20,30,40,50};
piBPtr = aiB;
printf("Address of piBPtr : %d Contents of piBPtr : %d\n", &piBPtr, piBPtr);
printf("Address of aiB : %d Contents of aiB[0]:%d %d %d\n", &aiB, aiB[0], *piBPtr, *aiB);
printf(“piBPtr points to aiB[0] = %d\n", *piBPtr);

printf("\nI am accessing element aiB[3]!!\nLet see how many ways I can do it\n");
printf(“aiB[3] = %d\n", aiB[3]);
printf("*(piBPtr + 3) = %d\n", *(piBPtr + 3));
printf("*(aiB + 3) = %d\n", *(aiB + 3));
printf(“piBPtr[3] = %d\n\n", piBPtr[3]);

for(iIndex=0;iIndex<10;iIndex++)
printf(“aiB[%d] = %d\n", iIndex, *(piBPtr+iIndex));
return 0;
} EKT 120:Computer Programming
Arrays of Pointers
 Arrays can contain pointers
 For example: an array of strings
char *acSuit[4] = {“Hearts”,“Diamonds”,“Clubs”,“Spades”};

 Strings are pointers to the first character


 char * – each element of acSuit is a pointer to a char
 The strings are not actually stored in the array acSuit,
only pointers to the strings are stored

EKT 120:Computer Programming


Arrays of Pointers
acSuit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

acSuit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

acSuit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

acSuit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

 acSuit array has a fixed size, but strings


can be of any size

EKT 120:Computer Programming


Example
#include <stdio.h> Enter student[0] name : ali
#define N 5 You just entered :
int main() ali
{ Enter student[1] name : abu
char *acStudentName[N]; int i; You just entered :
abu
for(i=0;i<5;i++) Enter student[2] name : cheah
{ printf("Enter student[%d] name : ", i); You just entered :
scanf("%s", acStudentName + i); cheah
printf("You just entered :\n%s\n", acStudentName + i); Enter student[3] name : dali
} You just entered :
return 0; dali
} Enter student[4] name : gheeta
You just entered :
gheeta

EKT 120:Computer Programming

You might also like