Array Sizes

NSBCoding :: Coding :: C++

Go down

Array Sizes

Post  Admin on Sat Jun 04, 2011 10:52 am

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.
Code:
int array[100];
means it can only hold 100 items at max. If you tried to do:
Code:
array[101] = 5;
it will crash.

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.

Admin
Admin

Posts : 21
Join date : 2011-06-04

View user profile http://nsbcoder.board-directory.net

Back to top Go down

Re: Array Sizes

Post  Elusive on Sun Jun 05, 2011 8:36 am

Admin wrote:
Code:
int array[100];
means it can only hold 100 items at max. If you tried to do:
Code:
array[101] = 5;
it will crash.

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

View user profile

Back to top Go down

Re: Array Sizes

Post  Admin on Sun Jun 05, 2011 9:38 am

[quote="Elusive"]
Admin wrote: but isn't the array index zero-based?
yeah oops

Admin
Admin

Posts : 21
Join date : 2011-06-04

View user profile http://nsbcoder.board-directory.net

Back to top Go down

Re: Array Sizes

Post  Sponsored content


Sponsored content


Back to top Go down

Back to top

- Similar topics

NSBCoding :: Coding :: C++

 
Permissions in this forum:
You cannot reply to topics in this forum