1

I am trying to wrap my mind around arrays and pointers in C++.

I am trying to write a function that allocates memory for an int array of variable size. The array is then filled with random numbers and returned.

The problem I have is assigning values with pointers.

This is the function:

int* getArray(int length) {
    int* values = new int[length];
    for (int i=0; i<length; i++) {
        values[i]=i;
    }
    return values;
}

And it works just fine.

But, if I change it to this:

int* getArray(int length) {
    int* values = new int[length];
    for (int i=0; i<length; i++, values ++) {
        *values=i;
    }
    return values;
}

It doesn't work.

Can someone explain to me why I cannot do this?

This is the main method that I used to print all the values:

int main() {
    int* v = getArray(100);
    for(int i=0;i<100;i++, v++) {
        cout << *v <<endl;
    }
    delete[] v;
    return 0;
}

I think it is because the new operator allocates new memory in the heap and not in the stack so the pointer might actually point to the wrong direction.

But, if that is true, why is the main method working?

Side note: I do not get any kind of warning or error, but the output is just a bunch of zeros and some random numbers.

I am using the GCC compiler on Ubuntu.

2
  • 2
    An array is represented by a pointer to its first element. In your second example you don't return a pointer to the first element. Commented Aug 13, 2018 at 14:26
  • Once you figure things out, ditch what you have learned and use std::vector instead, then all these problems will go away Commented Aug 13, 2018 at 16:04

1 Answer 1

2

values++ is modifying values, which eventually forms the function return value.

i.e. you return one past the end of the allocated array. That in itself is perfectly legal C++.

But things go very badly wrong at the function call site: you access invalid elements of the array (which very informally speaking are your "random numbers"), and calling delete[] on that is also undefined behaviour. Boom!

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

1 Comment

To be clear, the pointer value you delete[] must be exactly what was returned by new [], or undefined behavior results. Whether it's pointing past the end or at the second element, Boom!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.