Array out of bounds
Barry Denton
basse42 at yahoo.com
Mon Apr 14 14:50:08 PDT 2008
Jarrett Billingsley Wrote:
> "Barry Denton" <basse42 at yahoo.com> wrote in message
> news:fu0hfh$29mq$1 at digitalmars.com...
> > from the examples I try to do
> >
> > int COUNT = 10000;
> > char [COUNT][] itemStrings ;
> > for (int i = 0; i < COUNT; i++) {
> >
> > itemStrings [i][] = ("item " ~ to!(char[]) (i));
> >
> > 2 problems -does not accept COUNT as the size
>
> You can't declare a statically-sized array with a non-constant value. If
> you know you will always have 10000 values, use:
>
> const int COUNT = 10000;
>
> If the number of values can vary at runtime, use a dynamically allocated
> array instead:
>
> char[][] itemStrings = new char[][](n, count);
>
> > and if I use char[10000] its OK but after compiles OK but index out of
> > bounds error given on itemStrings[][] line
>
> You haven't given any size to the second dimension of the array. You've
> declared the array reference but haven't actually created an array.
>
> Maybe you're getting the syntax confused. The C-style syntax:
>
> char itemStrings[COUNT][];
>
> becomes:
>
> char[][COUNT] itemStrings;
>
> in D. Your array:
>
> char[COUNT][] itemStrings;
>
> reads as "a dynamic array of statically-sized arrays of length COUNT of
> int". You read right-to-left. It seems you want the other way,
> char[][COUNT].
>
> Even then, your loop is still wrong. You are trying to slice-assign an
> array that doesn't exist. Simply take out the slice on the left-hand-side:
>
> itemStrings[i] = "item " ~ to!(char([])(i);
>
> And it will fill in itemStrings[i] with the new string.
>
>
Thanks !
More information about the Digitalmars-d-learn
mailing list