I am trying to learn on how you can return pointers to arrays, so that you can go around the whole "you can't return arrays in C/C++"-Problem.
I am a beginner in C++, but I know a lot about Java if that helps.
My code is this:
// Source.cpp
#include <iostream>
// Returns a pointer to an array that contains the digits 0 to 9.
int* test()
{
// Create the array.
int r[10] = {0,1,2,3,4,5,6,7,8,9};
// Return the address to the array.
return r;
}
// Simple function that takes an "pointer" array or a "normal" array and prints the elements of them.
void print_arr(const int arr[], const int length)
{
for (int i = 0; i < length; i++)
std::cout << i << ": " << arr[i] << std::endl;
}
int main()
{
// Test the printing function with an "normal" array containing the digits 0 to 9.
print_arr(new int[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 10);
// Insert a line break to make the output look more clean.
std::cout << std::endl;
// Print the "pointer" array that should contain the same as the temporary variable.
print_arr(test(), 10);
}
My output is this on the default "Debug" configuration in VS22: (language standard: ISO C++ 14, Windows SDK Version: 10.0, Platform Toolset: Visual Studio 2022 (v143))
0: 0
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
0: 529054832
1: 32759
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
My output is this on the default "Release" configuration in VS22: (language standard: ISO C++ 14, Windows SDK Version: 10.0, Platform Toolset: Visual Studio 2022 (v143))
0: 0
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
0: 0
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
I have simelar issues with the Debug configuration changing values magically in visual studio. In general I have no idea what differences are there between these two configurations. I look forward for some tips with the Visual Studio Coding enviroment in general :).
I tried giving the "pointer" array an offset of it's adress in line 10 by just adding 2 (return r + 2;
), which worked, but of course that only changed the adress and not the contents of the array in the memory, so the outputs of the second print_arr were the digits from 2 to 9:
0: 2
1: 3
2: 4
3: 5
4: 6
5: 5
6: 8
7: 9
8: -858993460
9: -858993460
As I said, it "magically" (for me) works by changing to the "Release" config.