0

I tried to make a tree with swift using fonctionnal way

here is my code:

//this code works
struct testArbre {
    var racine: Int?
}

let a0 = testArbre(racine:nil)



//this code stuck on error
struct arbre {
    var racine: Int?
        var feuilleGauche: arbre?
        var feuilleDroite : arbre?
}

let a1 = arbre(racine: 10, feuilleGauche: nil, feuilleDroite: nil)

let a2 = arbre(racine:5, feuilleGauche:nil, feuilleDroite:nil)

let a3 = arbre(racine:1, feuilleGauche: a1, feuilleDroite: a2);

and here is the error when running this code:

<unknown>:0: error: unable to execute command: Segmentation fault: 11
<unknown>:0: error: swift frontend command failed due to signal (use -v to see invocation)
Command /Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift failed with exit code 254
babasLH
  • 46
  • 4

1 Answers1

0

Structs are value types. Imagine how the struct would be initialized: You have a struct arbre, so the system will allocate memory for its members, which are an Int and a struct arbre, so the system will allocate memory for its members (an int and a struct arbre), so the system will allocate memory for its members (an int and a struct arbre) . . . -> crash

You need to make it a class.

If you want a struct containing a reference to the same type that is easily done with pointers in C.

Why does "typdef struct { struct S *s; } S;" containing a pointer to same type compile?

Community
  • 1
  • 1
Ralf
  • 32
  • 2