< Previous | Contents | Next >

Returning a Pointer

Before you can return a pointer from a function, you must specify that youre returning one. Thats what I do in the refToElement() header.

string* ptrToElement(vector<string>* const pVec, int i)

Returning Pointers 241


By starting the header with string*, Im saying that the function will return a pointer to a string object (and not a string object itself). To specify that a function returns a pointer to an object of a particular type, put an asterisk after the type name of the return type.

The body of the function ptrToElement() contains only one statement, which returns a pointer to the element at position i in the vector pointed to by pVec.

return &((*pVec)[i]);

The return statement might look a little cryptic, so Ill step through it. Whenever you come upon a complex expression, evaluate it like the computer doesby starting with the innermost part. Ill start with (*pVec)[i], which means the element in position i of the vector pointed to by pVec. By applying the address of operator (&) to the expression, it becomes the address of the element in position i of the vector pointed to by pVec.

Tra p

image

Although returning a pointer can be an efficient way to send information back to a calling function, you have to be careful not to return a pointer that points to an out-of-scope object. For example, the following function returns a pointer that, if used, could crash the program.

string* badPointer()

{

string local = "This string will cease to exist once the function ends."; string* pLocal = &local;

return pLocal;

}

That’s because badPointer() returns a pointer to a string that no longer exists after the function ends. A pointer to a non-existent object is called a dangling pointer. Attempting to dereference a dangling pointer can lead to disastrous results. One way to avoid dangling pointers is to never return a pointer to a local variable.

image