Printing Value From Array in C++

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;

}

>Solution :

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;

}

Leave a Reply