June 27, 2016 Dynamic array of objects | ||||
---|---|---|---|---|
| ||||
Hi, Today thought lets learn D. I am writing a compiler for a language and read D compiles very fast. Switched my compiler from C++ to D and ran my test suite to use D. Doing somethin wrong as creating array of objects gives me a segmentation fault Example import std.stdio; class Pair { float x; float y; this() { x = 0; y = 0; } } void main() { Pair[] arr; // segmentation fault on next line arr = new Pair[](10); arr[0].x = 3; arr[0].y = 4; writef("arr[0] = (%f,%f)",arr[0].x,arr[0].y); } |
June 27, 2016 Re: Dynamic array of objects | ||||
---|---|---|---|---|
| ||||
Posted in reply to gummybears | On Monday, 27 June 2016 at 22:00:15 UTC, gummybears wrote:
> Hi,
>
> Today thought lets learn D. I am writing a compiler for a language
> and read D compiles very fast.
> Switched my compiler from C++ to D and ran my test suite to use D.
> Doing somethin wrong as creating array of objects gives me a segmentation fault
>
> Example
>
> import std.stdio;
>
> class Pair {
> float x;
> float y;
> this() { x = 0; y = 0; }
> }
>
>
> void main() {
> Pair[] arr;
>
> // segmentation fault on next line
> arr = new Pair[](10);
> arr[0].x = 3;
> arr[0].y = 4;
> writef("arr[0] = (%f,%f)",arr[0].x,arr[0].y);
> }
You've allocated an array of 10 objects but didn't put any objects into it, so each of the entries is null (since classes are reference types in D). The line after the allocation fails as you try to access a null object.
Either fill out the array with new objects (`arr[0] = new Pair()`), or convert Pair to a struct (structs are value types).
|
Copyright © 1999-2021 by the D Language Foundation