Pointers and Addresses in C++

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

In C++, what does a pointer directly contain?

  • The data type of a variable.
  • The value of a variable.
  • The memory address of a variable. (correct)
  • The name of a variable.

What is the critical difference between a variable name and a pointer in how they reference values?

  • Both indirectly reference a value, but a variable name is more type-safe.
  • A variable name directly references a value, while a pointer indirectly references it. (correct)
  • A variable name indirectly references a value, while a pointer directly references it.
  • Both directly reference a value, but a pointer can change the value more easily.

Consider the declaration int* ptr, var;. Which of the following statements is true?

  • `ptr` is an integer, and `var` is an integer pointer.
  • `ptr` is an integer pointer, and `var` is an integer. (correct)
  • Both `ptr` and `var` are integers.
  • Both `ptr` and `var` are integer pointers.

In C++, which operator is used to obtain the memory address of a variable?

<p>&amp; (D)</p> Signup and view all the answers

What is the * operator commonly referred to when used with pointers?

<p>Dereferencing operator. (B)</p> Signup and view all the answers

Given the code:

int y = 10;
int* yPtr = &y;
cout << *yPtr;

What will be the output?

<p>The value of <code>y</code>. (D)</p> Signup and view all the answers

How should pointers be initialized in modern C++ to indicate that they do not point to any valid memory location?

<p>nullptr (B)</p> Signup and view all the answers

Which of the following describes a key advantage of using pass-by-reference with pointers?

<p>It allows modification of the original variable and avoids the overhead of copying large objects. (D)</p> Signup and view all the answers

What is the primary difference between passing an argument by value versus by reference with pointers?

<p>Pass by reference with pointers involves passing the memory address, allowing changes to the original variable, whereas pass by value passes a copy. (A)</p> Signup and view all the answers

If a function is designed to modify an argument passed to it, which method should be used?

<p>Pass-by-reference with pointers. (C)</p> Signup and view all the answers

What is the correct syntax to declare a built-in array of 10 integers named numbers?

<p>int numbers[10]; (C)</p> Signup and view all the answers

What happens if you provide fewer initializers than the size of a built-in array during initialization?

<p>The remaining elements will be value-initialized to zero (or <code>nullptr</code> for pointers). (D)</p> Signup and view all the answers

What happens if you provide too many initializers for a built-in array during declaration?

<p>A compilation error will occur. (C)</p> Signup and view all the answers

How do built-in arrays behave when passed as arguments to a function?

<p>The address of the array's first element is passed, allowing the function to modify the original array. (B)</p> Signup and view all the answers

What is the significance of declaring a built-in array parameter as const in a function?

<p>It prevents the function from modifying the elements of the array. (A)</p> Signup and view all the answers

Which of the following operations is NOT permitted on built-in arrays directly?

<p>Comparing two arrays using relational operators (e.g., <code>&lt;, &gt;</code>). (D)</p> Signup and view all the answers

What must a function that processes a built-in array typically receive as arguments?

<p>The built-in array's name and its size. (D)</p> Signup and view all the answers

What is a critical consideration regarding array-access expressions when using built-in arrays?

<p>You must manually ensure that array-access expressions use subscripts that are within the built-in array's bounds. (D)</p> Signup and view all the answers

Given a pointer ptr pointing to an integer, what does ptr + n do, where n is an integer?

<p>Increments the memory address stored in <code>ptr</code> by <code>n</code> multiplied by the size of an integer. (A)</p> Signup and view all the answers

If int arr[5] is declared and the first element is located at memory address 1000, what address does arr + 2 refer to (assuming integers are 4 bytes)?

<p>1008 (A)</p> Signup and view all the answers

Which operation is NOT typically allowed directly with void* pointers?

<p>Dereferencing the pointer. (D)</p> Signup and view all the answers

Under what condition are comparisons using relational operators ( <, >, <=, >=) meaningful when used with pointers?

<p>When the pointers point to elements within the same built-in array. (C)</p> Signup and view all the answers

Given int b[5]; and int* bPtr;, which of the following statements correctly assigns the address of the first element of array b to the pointer bPtr?

<p>bPtr = &amp;b[0]; (A)</p> Signup and view all the answers

If bPtr points to b[0] of array b, how can b[3] be accessed using pointer arithmetic?

<p>*(bPtr + 3) (A)</p> Signup and view all the answers

If bPtr points to the beginning of array b, how is the address of b[3] correctly expressed using pointer arithmetic?

<p>bPtr + 3 (D)</p> Signup and view all the answers

How can you access the value of the second element of an array arr using pointer notation, assuming ptr points to the beginning of arr?

<p>*(ptr + 1) (D)</p> Signup and view all the answers

What is a pointer-based string in C++?

<p>A built-in array of characters ending with a null character. (B)</p> Signup and view all the answers

How is a pointer-based string typically accessed?

<p>Via a pointer to its first character. (C)</p> Signup and view all the answers

When creating a built-in array of characters to hold a string, what critical consideration must be taken into account?

<p>The array must be large enough to store the string and its terminating null character. (C)</p> Signup and view all the answers

What is the modern recommendation for handling strings in C++?

<p>Use the string class from the string library. (D)</p> Signup and view all the answers

Which of the following describes a key difference between pointers and references?

<p>Pointers can be null, but references cannot. (C)</p> Signup and view all the answers

Which of the following statements is true about the memory allocation of pointers and references?

<p>Pointers have their own memory address, while references share the address of the object they refer to. (B)</p> Signup and view all the answers

Following the declaration int *ptr;, which of the following is an example of dynamic memory allocation?

<p>ptr = new int; (C)</p> Signup and view all the answers

Which of the following is a key benefit of using function pointers?

<p>They allow dynamic function selection at runtime. (A)</p> Signup and view all the answers

What is a primary advantage of using pointers with linked lists, trees, and other dynamic data structures?

<p>They allow efficient memory allocation and eliminate size constraints of arrays. (D)</p> Signup and view all the answers

When passing a 1D array to a function in C++, what are common strategies to provide the array's size information?

<p>Using an unsized array and a size parameter. (C)</p> Signup and view all the answers

Which method allows a function to determine the number of columns in a 2D array, when passed as a parameter?

<p>Passing the array along with the number of rows and columns. (C)</p> Signup and view all the answers

Flashcards

What is a Pointer?

Contains the memory address of a variable

Direct vs. Indirect References

A variable name directly accesses a value, while a pointer indirectly does.

Pointer Declaration

The '*' indicates the variable is a pointer. Applies only to that variable in declaration.

Address Operator (&)

The unary '&' operator obtains the memory address of its operand.

Signup and view all the flashcards

Dereferencing Operator (*)

Returns the value at the memory address the pointer holds

Signup and view all the flashcards

Null Pointers

They point to nothing; use nullptr (C++11), 0, or NULL.

Signup and view all the flashcards

Ways to Pass Arguments in C++

Value, reference and pointer

Signup and view all the flashcards

Pass-by-Reference with Pointers

The address of the argument is passed.

Signup and view all the flashcards

Built-In Array Declaration

Specify the type of elements and number of elements required

Signup and view all the flashcards

Initializing a Built-in Array

int n[]{50, 20, 30, 10, 40};

Signup and view all the flashcards

Array Name as a Pointer

Array name converts to the address of its first element

Signup and view all the flashcards

Valid Pointer Arithmetic

Increment (++), decrement (--), addition (+), subtraction (-).

Signup and view all the flashcards

When can Pointers be Assigned Each Other?

Same Type

Signup and view all the flashcards

Pointer-Based String

An array of characters ending with a null character ('\0').

Signup and view all the flashcards

Applications of Pointers

Memory allocation (heap), function pointers, and data structures.

Signup and view all the flashcards

Pointers vs. References: Memory

Pointers have a separate memory address; references share the original variable's address.

Signup and view all the flashcards

Pointers vs. References: Reassignment

Pointers can be reassigned; references cannot.

Signup and view all the flashcards

Pointers vs. References: Arithmetic

Pointers allow arithmetic operations for array and data structure manipulation, while references do not.

Signup and view all the flashcards

How is dynamic memory allocated with Pointers?

new and delete

Signup and view all the flashcards

Study Notes

Introduction

  • A pointer contais the memory address of a variable.
  • The address contains a specific value.
  • A variable name directly references value.
  • A pointer indirectly references a value.

Declaring Pointers

  • int* countPtr, count; declares countPtr to be of type int*, a pointer to an int.
  • countPtr is a pointer to an int.
  • count is an int, not a pointer to an int.
  • The * applies only to countPtr.
  • Each variable declared as a pointer must have a preceding *.
  • When * appears in a declaration its not an operator and indicates that the variable is a pointer
  • Pointers can be declared to point to an object of any data type.

Address & Operator

  • The address operator & is a unary operator that obtains the memory address of it's operand
  • int y{5}; is how to declare variable y
  • int* yPtr = &y; declares a pointer variable and assigns the address of y to yPtr.

Dereferencing

  • The unary * operator is commonly referred to as the indirection operator or dereferencing operator.
  • It returns an lvalue representing the object to which its pointer operand points.
  • If int y{5}; and int* yPtr = &y;, then cout << *yPtr; dereferences the pointer
  • The above displays the value of whatever yPtr is pointing to which in this case will print 5.

Null Pointers

  • Pointers should be initialized to nullptr (new in C++11) or to a memory address either when they're declared or in an assignment.
  • A pointer with the value nullptr "points to nothing" and is known as a null pointer.
  • In C++ versions before C++11, the value specified for a null pointer was 0 or NULL.
  • NULL is defined in library headers to represent the value 0.

Pass-by-Reference with Pointers

  • Three ways to pass arguments to a function
    • Pass-by-value
    • Pass-by-reference with reference arguments
    • Pass-by-reference with pointer arguments
  • Pointers can modify multiple variables or pass pointers to large data objects, avoiding overhead.
  • Pointers and the indirection operator accomplish pass-by-reference.
  • When calling a function with an argument for modification, the address of the argument is passed.

Built-in Arrays

  • Arrays specify the type of the elements and the number of elements an array requires with type arrayName[arraySize];
  • The compiler reserves the memory.
  • arraySize must be an integer constant greater than zero.
  • To reserve 12 elements for a built-in array of ints named c, the declaration is int c[12]
  • Elements of a built-in array are accessed using the subscript [] operator

Initializing Built-in Arrays

  • Array elements initialized using an initializer list like int n[5]{50, 20, 30, 10, 40};
  • A built-in array of 5 ints is created and initialized with the specified values.
  • With fewer initializers, the remaining elements are value-initialized. numeric types are set to 0, bools to false, pointers to nullptr
  • Too many initializers results in a compilation error.
  • When a built-in array's size is omitted, the compiler sizes it to the number of elements in the list.
  • int n[]{50, 20, 30, 10, 40}; creates a five-element array.

Passing Built-in Arrays to Functions

  • The value of a built-in array's name is implicitly convertible to the address of the built-in array's first element.
  • arrayName is converted to &arrayName[0]
  • Do not take the address & of a built-in array to pass, simply pass the array's name.
  • The called funtion can modify all the elements of a built-in array in the caller, unless the function is const.
  • Built-in array parameter can be declared in a function header as int sum(const int values[], const size_t numberOfElements)
  • The above header can be written as int sum(const int* values, const size_t numberOfElements)

Built-In Array Limitations

  • Arrays can not be sorted with relational and equality operators which must loops be compared element by element usingif (a1 < a2); //illegal
  • Arrays cannot be assigned as a1 = a2; //illegal
  • Arrays do not track their size, functions processing arrays require both the array's name and size as arugments
  • Arrays do not have automatic bounds checking. Code must ensure array-access expressions use subscripts within the array's bounds.

Pointer Expressions and Pointer Arithmetic

  • Pointers are valid operands in arithmetic, assignment, and comparison expressions.
  • C++ enables pointer arithmetic with these operations
    • increment ++
    • decrement --
    • integer added to a pointer + or +=
    • integer subtracted from a pointer - or -=
    • one pointer subtracted from another. This is appropriate only for pointers that point to elements of the same built-in array.

Pointer Expressions and Pointer Arithmetic - Example

  • If int v[5] has been declared and the first element is at memory location 3000, and pointer vPtr is initialized to point to v[0], then the value of vPtr is 3000.
  • For a machine using four-byte integers:
    • Variable vPtr can be initialized to point to v with int* vPtr{v}; or int* vPtr{&v[0]};
    • When an integer is added to or subtracted from a pointer, the pointer is incremented or decremented by that integer * the size of the memory object to which the pointer refers.
    • vPtr += 2; produces 3008 = from 3000 + 2 * 4
    • In the built-in array v, vPtr now points to v[2].

Some Pointer Properties

  • A pointer can be assigned to another pointer if both pointers are of the same type.
  • A void* pointer cannot be dereferenced.
  • The compiler knows an int* points to four bytes of memory (on a 4-byte machine) and dereferencing it creates an lvalue that is an alias for the int's four bytes.
  • A void* simply contains a memory address for an unknown data type.
    • One cannot dereference a void* because the compiler does not know the type or number of bytes.
  • Pointers can be compared using equality and relational operators.
    • Comparisons using relational operators are meaningless unless the pointers point to the same built-in array.
    • Pointer comparisons compare the addresses stored in the pointers.

Relationship Between Pointer and Built-in Arrays

  • Given int b[5] creates a 5-element int array b, where b is a const pointer, and given that int* bPtr creates an int pointer bPtr, which isn't a const pointer.
  • Set bPtr to the address of the first element in the built-in array b with: bPtr = b;
  • The above is equivalent to assigning the address of the first element as follows: bPtr = &b[0];

Relationship between Pointer and Built-in Arrays: Array Elements

  • Built-in array element b[3] can alternatively be referenced with the pointer expression *(bPtr + 3)
    • The 3 is the offset to the pointer.
    • The parentheses are necessary because the precedence of * is higher than that of +.
  • Just as the built-in array element can be referenced with a pointer expression, the address &b[3] can be written with the pointer expression bPtr + 3.
  • The built-in array name can be treated as a pointer and used in pointer arithmetic.
    • The expression *(b + 3) refers to the element b[3].
  • All subscripted built-in array expressions can be written with a pointer and an offset.
  • Pointers can be subscripted exactly as built-in arrays.
    • The expression bPtr[1] refers to b[1].

Pointer Based Strings

  • A string is a series of characters treated as a single unit including letters, digits and special characters such as +, -, *, / and $.
  • A pointer-based string is a built-in array of characters ending with a null character \0.
  • Access a string via a pointer to its first character.
  • String literals may initialize built-in char arrays or const char* variables.
  • The built-in array of chars containing a string needs enough space for the string and its null terminator.
  • It is better use to strings from <string> than pointer-based strings.

Pointers vs References

  • References requires one step initialization.
int a{10}, b{20};
int *p;
p=&a;
int &r; // this is incorrect should declare and initialize reference at same step
r= a; // this is incorrect should declare and initialize reference at same step int &r=a
  • Pointers can be declared and initialized to Null, but a reference cannot
  • Memory distinctions:
  • Pointers have their own memory address and size in memory
  • References share the memory address of its object
Cout<<&a<<" "<<&p<<" "<<&r<<endl; // a and r have the same address but p has a distinct address

Pointers vs References (contd)

  • Reassignment differences
p=&b; // this is allowed for pointers
r=b // reassignment not allowed with references
  • Multiple indirection levels
    • Pointers can can be a pointer to pointer (Int **pp=&p; // ok)
    • References will give an error when using multiple levels (Int &&rr=&r; // this will give an error)
  • Pointers have pointer arithmetic which allow you to work with arrays or data structures like linked lists. There is no such thing as reference arithmetic

Other Applications of Pointers

  • Dynamic Memory Allocation using Heap memory
    • Pointers allocate memory dynamically during runtime usingnew and delete.
  • Example
int* arr = new int[5]; // Allocates an array of size 5 on the heap 
// Assign values
for (int i = 0; i < 5; i++) { 
    arr[i] = i * 10;
}
// Free memory to avoid memory leaks 
delete[] arr;
  • Pointers to Functons allow flexible functions
#include <iostream>
using namespace std;

void hello() { cout << "Hello, World!\n"; }
void bye() { cout << "Goodbye!\n"; }

void execute(void (*func)()) { func(); } // Function pointer

int main() {
    execute(hello); // Calls hello()
    execute(bye);   // Calls bye()
}
  • Dynamic data structures use linked lists, trees, and graphs
struct Node {
    int data;
    Node* next; // Pointer to the next node 
};

Passing 1D array to functions

  • Unsized array + size
void printarray(int a[],int size) // signature
printarray(a,size) // Passing array to function
  • As pointer + size
void printarray(int* a, int size)
printarray(a,size)
  • As reference
void printarray(int (&a) [size], int size)
printarray(a,size)

Passing 2D array to functions

  • Array + size
void printarray(int a[] [10],int r, int c)
printarray(a,r,c); // Passing array to function
  • pointer to array + size:
void printarray(int (*a) [10],int r, int c) // 10 is number of columns
printarray(a,r,c); // Passing array to function
  • reference to array + size:
void printarray(int (&a) [10],int r, int c) // 10 is number of columns
printarray(a,r,c); // Passing array to function

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser