This is a simplified code to explain the problem:
int *nums[10];
*nums[0] = 5;
cout << *nums[0] << endl;
The code compiled, but it fails when it executes. So I tried this:
int *nums[10];
*nums[1] = 5;
cout << *nums[1] << endl;
and it prints out fine. I figured out that array was starting from *nums[1] to *nums[10]
instead of the usual *nums[0] to *nums[10]. I’ve checked with others who use the Netbeans C/C++ compiler and theirs work as it should. I assume that it is some preference changed within the specific compiler. How do I change it so it works the way it should?
Arrays are 0-based. You’re running into undefined behavior.
creates an array of 10 uninitialized pointers to
int.dereferences an uninitialized pointer. Anything can happen. For it to behave as expected, allocate memory before accessing the pointers:
and delete it at the end:
For example, I get a warning in MSVS:
and also a crash :).