0

Our professor taught us to use an indirection operator (*) when accessing a dynamic variable. Hence, I fail to understand why the code is written like this:

cout << arr[i];

And not like this:

cout << *arr[i];


Here is the entire code:

#include <iostream>

using namespace std;

int main()
{
    int size;
    int *arr;

    cout << "Please enter size: ";
    cin >> size;

    arr = new int[size];

    cout << "Enter " << size << " items" << endl;
    
    for (int i = 0; i < 5; i++)
    {
        cin >> arr[i];
    }

    cout << "You entered: ";
    for (int i = 0; i < 5; i++)
    {
        cout << arr[i] << " ";
    }
}
1
  • Just as a note, you are missing the delete[] at the end. If you dont want to write it, you can use std::unique_ptr<T[]> Commented Jan 9, 2021 at 1:12

1 Answer 1

1

For arrays like you have:

arr = new int[size];

The syntax:

arr[5];

Is equivalent to this:

*(arr+5)

It's just nicer looking.

Sign up to request clarification or add additional context in comments.

2 Comments

And the professor I had for CS101 (introduction to C) in the mid-90s would knock off points if you ever used the [] or -> operators. And he never gave what I consider a convincing argument as to why, just "because I can".
World's full of strange people, @SoronelHaetir . Warning to those that follow. Because of the rules outlined in the post above, you can take a pointer to a single object and use it as an array to very unfortunate effects. Say you have int x; and then you int * xp = &x; to get a pointer to x. Now you can xp[1] = 42; and write over memory that is one integer past x. Not a good idea. Syntactically correct, so it compiles, but logically incorrect. This is a nice example: ideone.com/n4ZcaP. IDEOne tells you you screwed up. Don't count on this level of niceness. C++ is cruel.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.