Array Sizes
2 posters
Array Sizes
Some of you had trouble with array sizes, so i'll clarify some stuff.
The size you give an array is the MAXIMUM number of items it can hold.
Some of the tasks I give you will require different array sizes. You can do this by first asking for the size of the array:
Don't ever do this:
n is uninitialized, which means it can be ANY value, so it will most likely crash.
The size you give an array is the MAXIMUM number of items it can hold.
- Code:
int array[100];
- Code:
array[101] = 5;
Some of the tasks I give you will require different array sizes. You can do this by first asking for the size of the array:
- Code:
int n;
cout << "array size please: "
cin >> n;
int array[n];
Don't ever do this:
- Code:
int n; // uninitialized
int array[n];
n is uninitialized, which means it can be ANY value, so it will most likely crash.
Re: Array Sizes
Admin wrote:means it can only hold 100 items at max. If you tried to do:
- Code:
int array[100];
it will crash.
- Code:
array[101] = 5;
I'm not familiar with C++, but isn't the array index zero-based? i.e. if you declare an array of size 100, the indexes you can access are from 0 to 99?
Therefore, array[100] = 5; would also crash..
The highest index you can access is one (1) less than the size you declared the array as; the indexes start at 0, not 1.
- Code:
int n = 100;
int array[n];
// Highest accessible index
array[n - 1] = 5;
Elusive- Newbie
- Posts : 10
Join date : 2011-06-04
Permissions in this forum:
You cannot reply to topics in this forum
|
|