0

I have run this code:

#include <iostream>
using namespace std;

int* make_array(int a, int b, int c) {
    int results[3] = { a, b, c };
    return &results[0];
}

int main() {
    int *results = make_array(5, 2, 3);

    for (int i = 0; i < 3; i++) {
        cout << "\narray member N:" << i << ": " << *results;
        results++;
    }
    return 0;
}

As I understand, results variable holds address of first member of array [5, 2, 3] (address of 5). When I do results++ address should move 32 bits forward, so that results should be address of 2, but it logs following:

array member N:0: 5
array member N:1: 1434567088
array member N:2: 541456720

What am I doing wrong?

karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • You're returning a temporary which is undefined behaviour. – 101010 Oct 31 '15 at 13:17
  • 3
    You want to return an array, so return something that represents an array without loss of information like pointers have. The prime choice would be `std::array`. – chris Oct 31 '15 at 13:22
  • @101010 , chris, I read original question and understood everything. Thank you ^_^ – karaxuna Oct 31 '15 at 13:48

0 Answers0