www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Dynamic array of objects

reply gummybears <oracleopp gmail.com> writes:
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);
}
Jun 27 2016
parent Alex Parrill <initrd.gz gmail.com> writes:
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).
Jun 27 2016