Access Violation Error & Rectangular Arrays
Derek Parnell
derek at nomail.afraid.org
Mon Aug 21 19:10:02 PDT 2006
On Tue, 22 Aug 2006 01:44:26 +0000 (UTC), xycos wrote:
> Hello,
>
> I apologize for asking such n00bish questions... I come from a C#/Java
> background, and have never programmed with explicit pointers before.
>
> Two questions -- First, why won't this work?
Why do you need explicit pointers? This works ...
class Bar {
public Foo[5] arr;
public this() {
for(int i = 0; i < 5; i++) {
arr[i] = new Foo(i);
}
}
}
Remember that a class object variable is really a reference to the object
sitting on the heap - a pointer if you will.
> It gives me an "access violation"... The GC shouldn't have killed
> anything; I still have pointers, neh?
Your original code has ...
class Bar {
public Foo*[5] arr;
public this() {
for(int i = 0; i < 5; i++) {
Foo z = new Foo(i);
arr[i] = &z;
}
}
}
The '&z' phrase takes the address of the local variable 'z' and not the
address of the object on the heap.
> Second question: Is there any way to define a rectangular array (one
> of the optimized ones, not the dynamic-arrays-of-arrays things) that
> has its size determined at compile time?
Not yet. This is planned for v2 of D. Until then you need to do some of the
work yourself y using a single-dimension array and calculating the offsets
yourself.
int x[5,6] is equivalent to x[30]
If you want to reference i,j then you calc the index as x[i*5+j]
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
22/08/2006 11:56:25 AM
More information about the Digitalmars-d-learn
mailing list