www.digitalmars.com         C & C++   DMDScript  

D - Dynamic array initialization access violation

reply DDevil <ddevil functionalfuture.com> writes:
Try this code:

int main()
{
    int[] test;
    test[0..10] = 0;
    return 0;
}

Crashes... Is that suppose to happen?

--
// DDevil
Mar 08 2003
parent reply "Mike Wynn" <mike.wynn l8night.co.uk> writes:
it should throw an null pointer or array index exception
test is null (although ~= item or .length =  is allowed on a null array)
i.e.
int [] test;
test ~= 0;

try this instead
int main( char[][] args )
{
 int[] test = new int[10];
 test[0..10] = 0;
 return 0;
}
or
int main( char[][] args )
{
 int[] test;
 test.length = 10;
 test[0..10] = 0;
 return 0;
}



"DDevil" <ddevil functionalfuture.com> wrote in message
news:b4d0pj$dqd$1 digitaldaemon.com...
 Try this code:

 int main()
 {
     int[] test;
     test[0..10] = 0;
     return 0;
 }

 Crashes... Is that suppose to happen?

 --
 // DDevil

Mar 08 2003
parent reply DDevil <ddevil functionalfuture.com> writes:
Mike Wynn wrote:
 it should throw an null pointer or array index exception
 test is null (although ~= item or .length =  is allowed on a null array)

That's what I thought. Instead I get an access violation. For some reason I had it in my head that dynamic arrays would automatically allocate themselves. I understand now. So how to I allocate a dynamic multidimensional array? This seems logical but does not work: int[][] test = new int[10][10]; The following works for the first dimension, but how do I initialize the second without manually looping through every element? (that seems tedious): int[][] test = new int[][10]; // now what? loop? Thanks! -- // DDevil
Mar 08 2003
parent "Mike Wynn" <mike.wynn l8night.co.uk> writes:
only the last dimension can be dynamic

int main( char[][] args )
{
 int[10][] test = new int[10][10];
 return 0;
}

but

int main( char[][] args )
{
 int[][] test;
 test ~= new int[1];
 return 0;
}

works, ask Walter why this is.


"DDevil" <ddevil functionalfuture.com> wrote in message
news:b4d2ra$eia$1 digitaldaemon.com...
 Mike Wynn wrote:
  > it should throw an null pointer or array index exception
  > test is null (although ~= item or .length =  is allowed on a null

 That's what I thought.  Instead I get an access violation.

 For some reason I had it in my head that dynamic arrays would
 automatically allocate themselves.  I understand now.

 So how to I allocate a dynamic multidimensional array?

 This seems logical but does not work:
 int[][] test = new int[10][10];

 The following works for the first dimension, but how do I initialize the
 second without manually looping through every element? (that seems

 int[][] test = new int[][10];
 // now what? loop?

 Thanks!

 --
 // DDevil

Mar 08 2003