www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Access Violation Error & Rectangular Arrays

reply "xycos" <xycos u.washington.edu> writes:
Hello,


background, and have never programmed with explicit pointers before.

Two questions -- First, why won't this work?

int main(char[][] args) {

    Bar baz = new Bar();
    for(int i = 0; i < 5; i++) {
        writefln(baz.arr[i].x);
    }
    return 0;

}

class Foo {

    public int x;

    this(int y) {
        x = y;
    }

}

class Bar {

    public Foo*[5] arr;

    public this() {
        for(int i = 0; i < 5; i++) {
            Foo z = new Foo(i);
            arr[i] = &z;
        }
    }

}

It gives me an "access violation"... The GC shouldn't have killed
anything; I still have pointers, neh?

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?

Thanks!
Best of wishes,
Robert
Aug 21 2006
parent reply Derek Parnell <derek nomail.afraid.org> writes:
On Tue, 22 Aug 2006 01:44:26 +0000 (UTC), xycos wrote:

 Hello,
 

 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
Aug 21 2006
parent "xycos" <xycos u.washington.edu> writes:
Heh; that was fast! Thanks so much!
Aug 21 2006