Directly point to any element of dynamic-length number of elements without pointer arithmetic

58 views Asked by At

Is it possible to write a C++ program that allocates a user-inputted number of elements and gives them user-inputted values, and can then point directly to any element of those that have just been allocated, without having to use pointer arithmetic? I'm asking this because the human brain doesn't think that "the 7th element is the address of the first element + 6 steps ahead"; it can absolutely bind dynamically created elements and its current set of properties. If this is possible in C++, it would naturally speed up program execution.

Example code to clarify what I'm referring to:

//
//  main.cpp
//  This code doesn't compile
//  but it's for clarification purposes
//  Created by Måns Nilsson on 2017-01-02.
//  Copyright © 2017 Måns Nilsson. All rights reserved.
//

#include <iostream>

using namespace std;

int main(int argc, const char * argv[]) {
    int currval;
    int otherval;
    int arrlength;
    cout<<"How many elements would you like to allocate?"<<endl<<"Your input: ";
    cin >> arrlength;
    int numlist[arrlength];

    //User inputs the element values and variables are assigned to
    //point directly to each element
    for(int i=0;i<arrlength;i++) {
        cout<<"Enter a value for element "<<(i + 1)<<": ";
        cin >> currval;
        numlist[i] = currval;
        int &var(i) = numlist[i];
    }

        cout<<"Enter the index of the element you want to modify: ";
        cin >> currval;
        cout<<"Enter a new value for element "<<currval<<": ";
        cin >> otherval;
        var(currval-1) = otherval;

    return 0;
}
1

There are 1 answers

13
Serge Ballesta On

C++ allows to set up a reference to an element in a newly allocated array:

int *arr = new int[10];
int &elt6 = arr[6];
...
elt6 = 12; // actually sets arr[6]

The point here is that once you have defined your reference, you use it exactly like a normal variable sharing the memory of the array. But at some moment, you have to use pointer arithmetics to tell the compiler what array element you want to reference.