简体   繁体   中英

Netbeans c/c++ compiler array start at 1 instead of 0

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.

int *nums[10];

creates an array of 10 uninitialized pointers to int .

*nums[0] = 5;

dereferences an uninitialized pointer. Anything can happen. For it to behave as expected, allocate memory before accessing the pointers:

for ( int i = 0 ; i < 10 ; i++ )
   nums[i] = new int;

and delete it at the end:

for ( int i = 0 ; i < 10 ; i++ )
   delete nums[i];

For example, I get a warning in MSVS:

warning C4700: uninitialized local variable 'nums' used

and also a crash :).

In C/C++, arrays are always 0-indexed.

I am assuming you want to create an array of integers. If you want to create an array of pointers to integers, check out Luchian's answer.

You declared an array of 10 pointers to integer values. You did not allocate memory for the actual values. That is why you get an error.

You need to allocate memory for the integers. For this, you have two methods:

int nums[10];
nums[0] = 5;
cout << nums[0] << endl;

or

int* nums = new int[10];
nums[0] = 5;
cout << nums[0] << endl;
delete[] nums; // don't forget to delete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM