Menu
Coddy logo textTech

Pointers & Arrays

Lesson 6 of 14 in Coddy's C++ Pointers course.

Now that you learned about constant pointers and pointers to constants and you know the difference between, we can move on to the relation between pointers and arrays.

When we declare an array the name of the array is actually a constant pointer to a non-constant value, so the address that the pointer points to is constant and can't be changed, while the value it holds can. 

If we have int list[10];, here list is actually int * const, and list actually has the same value as &list[0]


int list[] = {10, 20, 30, 40, 50};
cout << "First: " << *list << endl;
cout << "Third: " << *(list + 2) << endl;
int *ptr = list;
cout << "First again: " << *ptr;
Output:
First: 10
Third: 30
First again: 10

As you can see we can use the name of the array list as a pointer to the first element and perform the tasks we need, the only setback when using the array pointer itself is that we can't change it, while when we create a pointer ptr to point to the same memory as list we can later on change its location in the program, for example:


int list[] = {10, 20, 30, 40, 50};
int *ptr = list;
for(int i = 0; i < 5; i++)
    cout << *ptr++ << " ";
Output:
10 20 30 40 50

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Don't change any of the default code, an array called numbers has been created using the numbers pointer and dereferencing print out all of the even elements that are in the array separated with a whitespace

Try it yourself

#include <iostream>

using namespace std;

int main() {
    // DO NOT CHANGE THE CODE BELOW
    int n, x;
    cin >> n;
    int numbers[n];
    for(int i = 0; i < n; i++)
        cin >> numbers[i];
    // DO NOT CHANGE THE CODE ABOVE

    // Enter your code here

    return 0;
}

All lessons in C++ Pointers