# Objects - faculty.winthrop.edu Pointers Topics Pointers Pointer Arithmetic Pointers and Arrays Objectives on completion of this topic, students should be able to: Correctly use pointers in a C++ program * Take the address of a variable * Dereference a pointer * Do pointer arithmetic

Explain the relationship between an array and a pointer * Use pointers to access array elements Pointers are one of the most powerful but most difficult concepts to master in programming. Languages like C# dont use pointers, except under special conditions, because they are so difficult. Assume that we have declared an integer variable v1, and that the compiler has assigned the memory location 000032 for that integer value.

000032 v1 is the name of the variable. if integer variables take up 4 bytes We can access the variable by of memory on this computer, then simply using its name. the address of the first byte of the integer is 000032. v1 = 34; The address of the variable is 000032.

000032 We can store the address of a variable in a special data type called a pointer. this statement declares the integer variable v1. Let us assume that the address of v1 in memory is 000032. int v1; this statement declares v1Ptr to be a variable of type integer pointer. That is, v1Ptr can contain a pointer

to (the address of) an integer. int *v1Ptr; v1Ptr = &v1; Note that pointers are typed. This pointer points to an integer. To declare a pointer variable, place an asterisk in front of the variable name. this statement stores the address of the variable v1 in the variable v1Ptr. The & is called the address-of operator.

v1 000032 000036 000032 v1Ptr v1Ptr is said to point to v1.

int v1; int *v1Ptr; v1Ptr = &v1; the asterisk used as shown here is called the de-referencing operator. *v1Ptr = 45; This statement says store the value 45 in the variable pointed to by v1Ptr. cout << v1;

000032 45 000036 000032 v1 v1Ptr Be careful when declaring pointers!

int *aptr, bptr; but bptr is an int! aptr is a pointer you must declare them this way! int *aptr, *bptr; Null Pointers There is a special value nullptr that is used to indicate that a pointer does not point to anything.

When first declaring a pointer, it is a good idea to set its value to nullptr, like this: int* intPtr = nullptr; You cannot dereference a null pointer. You should always test a pointer before you use it, to make sure it is not a NULL pointer: if (intPtr != nullptr) ... Pointer Assignment int v1, v2; v1

45 000032 000036 v2 int *v1Ptr, *v2Ptr; v1Ptr = &v1; *v1Ptr = 45; v2Ptr = v1Ptr; *v2Ptr = *v1Ptr;

v1Ptr 000032 000040 v2Ptr 000032 000044

Some Other Examples char *pc; // a pointer to a character char **pc; // a pointer to a pointer to a character char *pc; // an array of pointers to characters

void Pointer Recall that pointers are typed. int x = 3; int *xPtr; float *yPtr; xPtr = &x; yPtr = xPtr; this assignment wont work because the pointer types are not the same! The void pointer is a generic pointer type. That is, it can

hold the address of any data type. So, we could use a void pointer to write int x = 3; int *xPtr; void *yPtr; xPtr = &x; Now this statement will compile and execute with no errors because yPtr is a generic pointer. yPtr = xPtr;

int x = 3; int *xPtr; void *yPtr; xPtr = &x; However, this statement will not work. Because a void pointer is generic, it does not keep track of what kind of data it points to. Therefore, the computer cannot do the conversion necessary to print out the data pointed to by the void pointer.

yPtr = xPtr; cout << *yPtr; Casting int x = 3; int *xPtr; void *yPtr; xPtr = &x; yPtr = xPtr; If we know what the data type is that the pointer points to, we can cast the pointer to the correct type to make the statement work.

cout << *(static_cast(yPtr) ); The type we are casting to, in this case an int* appears in parenthesis in front of the variable name. Pointers and Arrays The name of an array is really a const pointer to the first element in the array! myArray int myArray ;

* myArray is an integer pointer. * myArray is a const pointer ( so that the address of myArray is not accidentally lost!) * myArray can be assigned to a pointer variable. Array/Pointer Duality Law a[n] is identical to *(a + n) where a is a pointer to an array and n is an integer offset. #include

using namespace std; int main ( ) { int intArray[ ] = {1, 3, 5, 7, 9}; cout << "\nintArray = " << intArray; cout << endl; return 0; } what will this statement display? #include

using namespace std; int main ( ) { int intArray[ ] = {1, 3, 5, 7, 9}; cout << "\nintArray = " << intArray; cout << \n*intArray = << *intArray; cout << endl; return 0; } what will this statement display?

Pointer Arithmetic Since a pointer is just a normal variable we can do arithmetic on it like we can for any other variable. For example int *myPtr; myPtr++; // increment the pointer myPtr--; // decrement the pointer

myPtr += 4; // add four to myPtr Note however, that in C++, pointer arithmetic is only meaningful within an array. address int x; X 5

000016 int *aPtr; X 8 000020 aPtr = x;

aPtr 000016 000020 000024 *aPtr = 5; aPtr++; *aPtr = 8; Note: When we increment a pointer, we increment it by the size of the data type it points to!

Note the following interesting use of pointers and arrays. int myArray ; int* arrayPtr; arrayPtr = myArray; myArray  = 125; *(arrayPtr + 3) = 125; these are all equivalent. *(myArray + 3) = 125; arrayPtr  = 125;

the assignment works because myArray is an int pointer. use pointer arithmetic to move the pointer to the 4th element in the array (3 times size of int) aha you can also use pointer arithmetic on the array name. and index notation on the pointer. Great care should be taken when using pointer arithmetic to be sure that the

pointer always points to valid data. Pointers and C-Strings Recall that a C-style character string is just an array of characters that is null terminated. char msg[ ] = Hello World; H e l l o W o r l d \0 Pointers and C-Strings

The name of the array is a constant pointer to the first character in the array. char msg[ ] = Hello World; H e l l o msg W o r l d \0 Functions that Return Arrays A function cannot return an entire array, that is, the following is illegal:

int [ ] someFunction ( ); To create a function that achieves the desired result, write the function so that it returns a pointer of the base type of the array, for example: int* someFunction ( ); Warning: dont return a pointer to data declared locally inside of the function! The -> Operator We normally use the dot operator to reference member data or Member functions in an object. For example myCircle.getArea( );

But if we have a pointer to the object we have to use the -> operator, like this myCirclePtr->getArea( ); The pointer this Every object contains a data member named this, that contains the address of the object itself. The implicit parameter When you send a message to an object, for example myCircle.getArea( ); The object that you send the message to is called the implicit parameter of the message. So, the this

pointer points to the implicit parameter (i.e. the object You are sending the message to). The implicit parameter So, in the function myCircle.getArea( ); You could write double Circle::getArea( ) { return this->radius * this->radius * PI; } i.e. this->radius refers to the radius data member in the object receiving the getArea message.

Practice. variable name address value in memory int x; int y; int *p = &x; int *q = &y;

*p = 35; *q = 98; x 1000 y 1004 p

1008 q 1012 variable name address value in memory int x;

int y; int *p = &x; int *q = &y; x = 35; y = 46; p = q; *p = 78; x 1000 y

1004 p 1008 q 1012 Given the definitions double values[ ] = {2, 3, 5, 17, 13};

double *p = values + 3; Explain the meaning of: values values + 1 *(values + 1) p p+1 p - values Suppose that you had the char array T h i s

i s if you had a pointer, cPtr, that pointed here g o o d . and you put a null terminating character here then the statement cout << cPtr;

would display the word is Review of functions to manipulate char arrays strcat(char *str1, char *str2); strcmp(char *str1, char *str2); strcpy(char *str1, char *str2); strlen(char *str); Common Pointer Errors

Trying to dereference a NULL or uninitialized pointer Confusing pointers with the data to which they point Returning a pointer to data declared locally in a function Pointers to Functions Suppose that you wanted to display a table of values like this: x f(x) = x2 1

2 3 4 1 4 9 16 You could write this function: void printTable( ) {

for (int x = 0; x < 10; x++) { int y = x * x; cout << x << \t << y << endl; } } But suppose that you also wanted to output a table of x and f(x) = x - 1? or x and f(x) = x or

Function Pointers In C++ it is possible to pass the address of a function as a parameter to another function. The prototype for such a function looks like this: void doSomething( int (*f)(int) ); This is a pointer to a function * The function takes an integer parameter * The function returns an integer Lets write a function to compute the square of an integer:

int square(int n) { return n * n; } and write the function to print a table like this: pointer to a function void printTable(int (*f)(int) ) { cout << setprecision(2); for (int x = 1; x < 10; x++)

{ call the function f int y = f(x); cout << x << '\t' << y << endl; } } To pass this function as a parameter to the printTable function, we simply pass the functions name like this: printTable (square); The power in this approach is that the printTable function can now print a table of the integers 1 through 10 and some

value that is computed on each of those integers. But the printTable function doesnt know what calculation it is going to do. That knowledge is passed to printTable as a pointer to the function that actually does the calculation in this case, the square function.