Back to C++
2026-02-238 min read

Example 2: Array name used as pointer (C++)

Learn Example 2: Array name used as pointer (C++) step by step with clear examples and exercises.

Why This Matters

In C++, understanding the behavior of array names as pointers is crucial for mastering pointer concepts and solving complex programming problems efficiently. This lesson will delve deeper into this topic, providing examples and best practices to help you use this powerful feature. Let's get started!

Why This Matters

Arrays are a fundamental data structure in C++, but they can also behave like pointers under certain circumstances. Familiarizing yourself with this behavior will not only make your code more efficient but also prepare you for real-world programming scenarios and interviews.

Advantages of Using Array Names as Pointers

  1. Simplified function arguments: Passing arrays as function arguments allows you to treat them like pointers, making it easier to manipulate the data inside the function.
  2. Flexible initializer lists: When initializing arrays with other arrays or individual elements, array names decay into pointers, enabling more flexible and concise code.
  3. Assigning arrays to pointer variables: This allows you to work with arrays using pointers, providing more flexibility when manipulating data.

Prerequisites

To follow along with this lesson, you should be comfortable with the following topics:

  1. Basic C++ syntax (variables, operators, control structures)
  2. Understanding pointers in C++ (what they are, how to declare, and basic pointer operations)
  3. Array basics (declaration, initialization, and accessing elements)
  4. Pointer arithmetic and dereferencing
  5. Pointers to arrays and multi-dimensional arrays

Core Concept

In C++, an array name implicitly converts to a pointer of its element type when it is used in the following ways:

  1. As a function argument
  2. As the operand of the & (address-of operator)
  3. In certain initializer lists
  4. When assigned to a pointer variable
  5. As a return value from functions that allocate memory on the heap

Let's take a closer look at each case.

Array as Function Argument

When an array is passed as a function argument, it decays into a pointer to its first element:

void printArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
}

int main() {
int numbers[] = {1, 2, 3, 4, 5};
printArray(numbers, sizeof(numbers) / sizeof(numbers[0]));
return 0;
}

In this example, the printArray function accepts an array as its first argument, which is then treated as a pointer to its first element. We pass our numbers array to the function and explicitly calculate its size using sizeof.

Array as Operand of & (Address-of Operator)

When the address-of operator & is applied to an array name, it returns a pointer to the first element of the array:

int* getFirstElement(int arr[]) {
return &arr[0];
}

int main() {
int numbers[] = {1, 2, 3, 4, 5};
int* firstNumber = getFirstElement(numbers);
std::cout << *firstNumber << "\n"; // Output: 1
return 0;
}

In this example, the getFirstElement function returns a pointer to the first element of the array. We can then dereference the pointer using the indirection operator * to access its value.

Array in Initializer Lists

When an initializer list includes an array, each element is initialized separately. In this case, the array name decays into a pointer:

int numbers[] = {1, 2, 3, 4, 5};
int anotherNumbers[5] = {numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]};

In this example, we initialize a new array anotherNumbers with the values from the numbers array. Since the initializer list includes an array, the array name decays into a pointer to its first element, which is then used to initialize the elements of the new array.

Array Assigned to Pointer Variable

When an array is assigned to a pointer variable, the pointer points to the first element of the array:

int numbers[] = {1, 2, 3, 4, 5};
int* numPtr = numbers;
std::cout << *numPtr << "\n"; // Output: 1

In this example, we assign the numbers array to a pointer variable numPtr. We can then dereference the pointer to access its value.

Array as Return Value from Functions Allocating Memory on the Heap

Functions that allocate memory on the heap and return a pointer can also return an array:

int* createArray(int size) {
int* arr = new int[size];
// Initialize the array...
return arr;
}

int main() {
int* numbers = createArray(5);
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
// ...use the array...
delete[] numbers; // Don't forget to deallocate the memory!
return 0;
}

In this example, our createArray function returns a pointer to an array of integers. We can then use this pointer to manipulate the data in the array and eventually deallocate the memory using delete[].

Worked Example

Let's work through an example that demonstrates using array names as pointers to solve a problem.

Problem Statement

Given two arrays, arr1 and arr2, of size n, write a function called findCommonElement that finds the common element (if any) between the two arrays.

int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 4, 5, 6, 7};
int n = sizeof(arr1) / sizeof(arr1[0]);

findCommonElement(arr1, arr2, n);

Solution

To solve this problem, we can iterate through both arrays using pointers and compare the elements:

void findCommonElement(int* arr1, int* arr2, int size) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
if (*(arr1 + i) == *(arr2 + j)) {
std::cout << *(arr1 + i) << " is the common element.\n";
return;
}
}
}
std::cout << "No common element found.\n";
}

In this solution, we pass both arrays to our findCommonElement function as pointers. We then iterate through each array using pointers and compare the elements. If a common element is found, we print it and return from the function.

Common Mistakes

  1. Forgetting to check for a common element when no such element exists. Always include a check for this case in your solution.
  2. Treating arrays as pointers without understanding their behavior. Be aware of how array names behave in different contexts, and use them appropriately.
  3. Not properly dereferencing pointer variables. Remember to use the indirection operator * when working with pointer variables.
  4. Confusing array indices with pointer arithmetic. Array indices are zero-based, but pointer arithmetic starts from the beginning of the memory location. Be careful when converting between the two.
  5. Not understanding pointer decay. When an array is passed as a function argument or used in certain initializer lists, it decays into a pointer to its first element. Understand this behavior and use it effectively.
  6. Not handling dynamic memory allocation correctly. Make sure to deallocate the memory allocated on the heap when you're done using it to avoid memory leaks.
  7. Not checking for array bounds when iterating through arrays with pointers. Always ensure that your pointers don't exceed the bounds of the array to prevent undefined behavior and potential security vulnerabilities.

Practice Questions

  1. Write a function called findSecondCommonElement that finds the second common element (if any) between two arrays.
  2. Given an array of integers, write a function called sortArray that sorts the array using bubble sort.
  3. Given an array of strings, write a function called reverseWordsInArray that reverses the order of the words in each string and the order of the strings in the array.
  4. Write a function called findMaximumSumSubarray that finds the maximum sum subarray within an array.
  5. Given two arrays, write a function called mergeArrays that merges the two arrays into a single sorted array.
  6. Write a function called countOccurrences that counts the number of occurrences of a specific value in an array.
  7. Write a function called findMedian that finds the median value of an array (assuming the array has an odd number of elements).
  8. Write a function called findMode that finds the mode (most frequent element) of an array.
  9. Write a function called reverseArray that reverses the order of the elements in an array.
  10. Write a function called rotateArray that rotates an array by a given number of positions.

FAQ

  1. Why does my code not compile when I try to pass an array as a function argument? Make sure you are declaring your function with the correct parameter type (a pointer). Also, check if you have included the necessary header files.
  2. What happens when I pass an array as a function argument without using pointers or references? In this case, the array decays into a pointer to its first element. However, you cannot modify the original array inside the function since it is treated as a constant. To allow modification, use pointers or references.
  3. Can I use arrays as function return types in C++? No, arrays cannot be used as function return types directly. Instead, you can allocate memory on the heap and return a pointer to that memory.
  4. What's the difference between an array and a pointer in C++? An array is a contiguous block of memory holding elements of the same type, while a pointer is a variable used to store the memory address of another variable or data structure. However, arrays can behave like pointers in certain contexts.
  5. Why do I need to understand how arrays decay into pointers? Understanding this behavior is essential for writing efficient and effective C++ code. It allows you to pass arrays as function arguments, use arrays in initializer lists, and assign arrays to pointer variables. Additionally, it helps you avoid common pitfalls and write more maintainable code.
  6. What are some best practices when using array names as pointers? Always be aware of the context in which array names are used, and understand how they behave in each case. Use pointers explicitly when working with dynamic memory allocation or when you need to modify arrays passed as function arguments. Lastly, ensure that your code handles array bounds correctly to prevent undefined behavior and potential security vulnerabilities.
Example 2: Array name used as pointer (C++) | C++ | XQA Learn