0

I have got a function declared like this:

uint8_t* func()
{
    uint8_t arr[8] = { 1,2,3,4,5,6,7,8 };
    return arr;
}

But when I try to read this data from a function - casted to unsigned:

uint8_t* readedArray = func();
for (int i = 0; i < 8; i++)
{
    cout << (unsigned int)readedArray[i] << endl; 
}

I'm not getting as a result

1
2
3
4
5
6
7
8

but something like this:

1
16
131
0
136
153
222
12

Why is it caused?

yeuop
  • 159
  • 1
  • 9
  • 6
    You are accessing the array after it no longer exists (it exists only inside of the function `func`). It's undefined behavior. – CherryDT Oct 16 '21 at 12:50
  • To make this work use auto func() { std::array arr{1,2,3,4,5,6,7,8}; return arr; }. "C" style arrays can't really be returned from functions very well. And strange as it may seem returning instances of local classes is defined behavior (C++ can be complicated like that see : https://en.cppreference.com/w/cpp/language/copy_elision) – Pepijn Kramer Oct 16 '21 at 13:00
  • I'm idiot. Thank you guys! – yeuop Oct 16 '21 at 13:27

0 Answers0