1

I want to write a method in C++ which creates an array of monotonically increasing values. It has the inputs of int begin, int end, int interval.

In this example; method should return the array of [0,1,2,3,4,5,6,7,8,9,10]. When I print the results it should print out the first two indexes and get 0 and 1. However, when I print it, it gives 0 for the first one and 9829656 for the second one.

When I only print one index it is always correct, but when I print more than one index, every value except for the first printed one gives a different result. I think the other results are related to memory address since I used pointers.

#include <iostream>
using namespace std;

int* getIntervalArray(int begin, int end, int interval){

    int len = (end - begin) / interval + 1;

    int result[11] = {};

    for (int i = 0; i <= len - 1; i++) {
        result[i] = begin + interval * i;
    }

    return result;
}

int main(){

    int begin = 0;
    int end = 10;
    int interval = 1;

    int* newResult = getIntervalArray(begin, end, interval);

    cout << newResult[0] << endl;
    cout << newResult[1] << endl;

    return 0;

}
user6210457
  • 397
  • 1
  • 7
  • 22
  • 2
    `int result[11] = {};` is local array and cannot be returned. You need to create dynamic array `int* result = new int[11]` in order to return that from function. But you need to remember to also `delete[]` that array, after using, so I would advice to use local array outside function and pass into function, or `new int[11]` and `delete[]` that outside with your current code, but it would look better using local array. – shjeff Nov 06 '21 at 18:13
  • [Compiler warnings want to help you!](https://godbolt.org/z/9c8bcsren) – Drew Dormann Nov 06 '21 at 18:17
  • That's a dangling pointer you're returning, see: https://stackoverflow.com/a/13132808/13113537. And if you're going to use dynamically allocated arrays with "new" or "malloc" also note the memory leak example. – Luiz Nov 06 '21 at 18:18
  • @shjeff why do I need to delete the newResult array? – user6210457 Nov 06 '21 at 18:18
  • 1
    @user6210457 because this is some kind of memory '(heap)' that you are borrowing and your program shouldn't steal/consume any bytes. By using `delete[]` you are telling OS that you don't need that memory anymore. – shjeff Nov 06 '21 at 18:21
  • See: https://stackoverflow.com/a/2308762/5558393 for more information about heap and stack memories difference. – shjeff Nov 06 '21 at 18:28

4 Answers4

4

You are returning a pointer to a local variable. You can instead return a std::vector by value as shown below:

#include <iostream>
#include <vector>
//return a vector by value
std::vector<int> getIntervalArray(int begin, int end, int interval){

    int len = (end - begin) / interval + 1;

    std::vector<int> result(len); //create a vector of size len

    for (int i = 0; i <= len - 1; i++) {
        result.at(i) = begin + interval * i;
    }

    return result;
}

int main(){

    int begin = 0;
    int end = 10;
    int interval = 1;

    std::vector<int> newResult = getIntervalArray(begin, end, interval);

    //print out elements of returned vector
    for(int i = 0; i < newResult.size(); ++i)
    {
        std::cout << newResult.at(i) << std::endl;
 
    }
    
    return 0;
}

The output of the above program can be seen here.

Jason
  • 36,170
  • 5
  • 26
  • 60
2

A possible solution dynamically allocating the local array, and returning it via a smart pointer:

#include <array>
#include <iostream>
#include <memory>  // make_unique

auto getIntervalArray(int begin, int end, int interval)
{
    int len = (end - begin) / interval + 1;

    auto result{ std::make_unique<std::array<int, 11>>() };

    for (int i = 0; i <= len - 1; i++) {
        (*result)[i] = begin + interval * i;
    }

    return result;
}

int main()
{
    int begin = 0;
    int end = 10;
    int interval = 1;

    auto newResult{ getIntervalArray(begin, end, interval) };

    std::cout << (*newResult)[0] << std::endl;
    std::cout << (*newResult)[1] << std::endl;
    std::cout << (*newResult)[2] << std::endl;

    return 0;
}

Demo

rturrado
  • 7,699
  • 6
  • 42
  • 62
2

Set the array variable in your function as static. This is because C++ does not support returning the address of a local variable.

static int result[11];
1

try this. also add deletion of the newResult

#include <iostream>
using namespace std;

int* getIntervalArray(int begin, int end, int interval){

    int len = (end - begin) / interval + 1;

    int* result = new int[len];
    int lastValue = begin;
    for (int i = 0; i <= len - 1; i++) {
        result[i] = lastValue;
        lastValue += interval;
    }

    return result;
}

int main(){

    int begin = 0;
    int end = 10;
    int interval = 1;

    int* newResult = getIntervalArray(begin, end, interval);

    cout << newResult[0] << endl;
    cout << newResult[1] << endl;
    
    // add delete here. 
 
    return 0;

}
Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28