Tech

Pointers–STRUCTURED PROGRAMMING Course Notes

Pointers

Pointer Variable Declarations & Initialization

  • Pointers are variables that contain as their values memory addresses of other variables.
  • The declaration: int *ptr; declares ptr to be a pointer to a variable of type int and is read, “ptr is a pointer to int.
  • The *(asterisk) as used here in a declaration indicates that the variable is a pointer.
  • There are 3 values that can be used to initialize a pointer:
    • 0,
    • NULL,
    • or, an address of an object of the same type.
  • The only integer that can be assigned to a pointer without casting is zero.
  • Normally, a variable directly contains a specific value. A pointer contains the memory address of a variable that, in turn, contains a specific value. In this sense, a variable name directly references a value, and a pointer indirectly references a value. Referencing a value through a pointer is called indirection.
  • Pointers, like any other variables, must be declared BEFORE they can be used.

Tip: Initialize pointers to prevent pointing to unknown or uninitialized areas of memory!!

The pointer is one of C++’s most powerful features!

Pointers keep track of where data & functions are stored in memory, which allows us to manipulate those items in interesting ways.

Pointer Operators

  • The &(address) operator obtains the memory address of its operand.
  • The operand of the address operator must be a variable name (or another lvalue); the address operator cannot be applied to constants or to expressions that do not return a reference.
  • The *indirection (or dereferencing) operator returns a synonym for the name of the object that its operand points to in memory. This is called dereferencing the pointer.
  • Ex:
    • int y = 5; //declare variable y
    • int *yPtr; //declare pointer variable yPtr
  • then the statement:
    • yPtr = &y; //assign address of y to yPtr

Now, variable yPtr is said to “point to” y. Now, yPtr indirectly references variable y‘s value. (Note: The use of the ‘&‘ (ampersand) in the preceding statement is not the same as the use of the ‘&‘ in a reference variable declaration, which is ALWAYS preceded by a data-type name. When declaring a reference, the & is part of the type. In an expression like &y, the ‘&‘ is an operator.)

Pass-by-Reference with Pointers

There are 3 ways in C++ to pass arguments to a function:

  • pass-by-value
  • pass-by-reference with reference pointers
  • and, pass-by-reference with pointer arguments

When calling a function with an argument that the caller wants the called function to modify, the address of the argument may be passed. The called function then uses the indirection operator (*) to dereference the pointer, and modify the value of the argument in the calling function.

A function receiving an address as an argument must have a pointer as it corresponding parameter.

Using “const” with Pointers

  • The “const” qualifier enables you to inform the compiler that the value of a particular variable cannot be modified through the specified identifier.
  • There are 4 ways to pass a pointer to a function:
    • a non-constant pointer to a non-constant data;
    • a non-constant pointer to constant data;
    • a constant pointer to non-constant data;
    • and, a constant pointer to constant data.
  • The value of the array name is the address of the array’s first element.
  • To pass a single array element by reference using pointers, pass the address of the array element.

Selection Sort Using Pass-By-Reference

The selection sort algorithm is an easy-to-program, but inefficient, sorting algorithm. The first iteration of the algorithm selects the smallest element in the array & swaps it with the first element. The second iteration selects the second-smallest element (which is the smallest element of the remaining elements) and swaps it with the second element. The algorithm continues until the last iteration selects the second-largest element, & swaps it with the second-to-last index, leaving the largest element in the last index. After the ‘i’th iteration, the smallest ‘i’ items of the array will be sorted into increasing order in the first ‘i’ elements of the array.

‘sizeof’ Operator

Operator ‘sizeof‘ determines the size (in bytes) of a data type, variable, or constant at compile time.

When applied to an array name, ‘sizeof‘ returns the total number of bytes in the array.

Pointer Expression & Pointer Arithmetic

  • The arithmetic operations that may be performed on pointers are:
    • incrementing (‘++‘) a pointer, decrementing (‘‘) a pointer,
    • adding (‘+‘ or ‘+=‘) an integer to a pointer
    • subtracting (‘‘ or ‘-=‘) an integer from a pointer,
    • subtracting one pointer from another.
  • When an integer is added or subtracted from a pointer, the pointer is incremented or decremented by that integer times the size of the object to which the pointer refers.
  • Pointers can be assigned to one another if they are of the same type. Otherwise, a cast must be used. The exception to this is a void * pointer, which is a generic pointer type that can hold pointer values of any type.
  • The only valid operations on a void * pointer are comparing void * pointers with other pointers, assigning addresses to void * pointers, and casting void * pointers to valid pointer types.
  • Pointers can be compared using the equality & relational operators. Comparisons using relational operators are meaningful only if the pointers point to members of the same array.

Relationship Between Pointers & Arrays

  • Pointers that point to arrays can be subscripted exactly as array names can.
  • In pointer/offset notation, if the pointer points to the first element of the array, the offset is the same as an array subscript.
  • All subscripted array expressions can be written with a pointer and an offset, using either the name of the array as a pointer or using a separate pointer that points to the array.

Pointer-Based String Processing

  • A character constant is an integer value represented as a character in single quotes. The value of a character constant is the integer value of the character in the machine’s character set.
  • A string is a series of characters treated as a single unit. A string may include letters, digits, & various special characters such as ‘+’, ‘-‘, ‘*’, ‘/’, and ‘$’.
  • String literals, or string constants, in C++ are written in double quotation marks.
  • A pointer-based string is an array of characters ending with a null character (‘\0’), which marks where the string terminates in memory. A string is accessed via a pointer to its first character.
  • The value of a string literal is the address of its first character, but the ‘sizeof‘ a string literal is the length of the string including the terminating null character.
  • A string literal may be used as an initializer for a character array or a variable of type ‘char*‘.
  • String literals have ‘static‘ storage class and may or may not be shared if the same string literal is referenced from multiple locations in a program.
  • The effect modifying a string literal is undefined; thus, you should always declare a pointer to a string literal as ‘const char*‘.
  • When declaring a character array to contain a string, the array must be large enough to store the string and its terminating null character.
  • *If a string is longer than the character array in which it’s to be stored, characters beyond the end of the array will overwrite data in memory following the array, leading to logic errors.
  • We can access individual characters in a string directly with array subscript notation.
  • A string can be read into a character array using stream extraction with ‘cin‘.
  • The ‘setw‘ stream manipulator can be used to ensure that the string read into a character array does not exceed the size of the array.
  • The ‘cin‘ object provides the member function ‘getline‘ to input an entire line of text into a character array. The function takes three arguments:
    • a character array in which the line of text will be stored,
    • a length,
    • and, a delimiter character.
    • The third argument has ‘\n’ as a default value.
  • A character array representing a null-terminated string can be output with ‘cout‘ and ‘<<‘. The characters of the string are output until a terminating null character is encountered.

Arrays of Pointers

  • Arrays may contain pointers.
  • Such a data structure can be used to form an array of pointer-based strings, referred to as a string array. Each entry in the array is a string, but in C++ a string is essentially a pointer to its first character, so each entry in an array of strings is simply a pointer to the first character of a string.
  • String arrays are commonly used with command-line arguments that are passed to ‘main‘ when a program begins execution.

Function Pointers

  • A pointer to a function is the address where the code for the function resides.
  • Pointers to functions can be used to call the functions they point to, passed to functions, returned from functions, stored in arrays, assigned to other pointers.