Could anybody please explain what's wrong with this C++ code? I can see that you cannot return an array in C++ (like in other languages) so I'm returning a pointer. I learned that there's no point in setting the pointer to the address of "myArray" - because "myArray" is already an address (first item)
the output I expected was 1,2,3,4
on different (online) compilers I'm getting different weird results here, including:
- 1, 4, -993994160, 32767
- 1, -1077229596, -1077229588, 1075514957
- 1,2,3,3 (so close)
so here's my dodgy code:
#include <iostream>
using namespace std;
int* getArray(){
int myArray[] = {1,2,3,4};
int* pointerToArray = myArray;
return pointerToArray;
}
void printArray(int inputArr[], int length) {
for (int i = 0; i < length; i++) {
cout << inputArr[i] << ", ";
}
}
int main()
{
printArray(getArray(),4);
return 0;
}
any help you could provide is VERY much appreciated!