elliotchance / c2go

⚖️ A tool for transpiling C to Go.
MIT License
2.07k stars 154 forks source link

Can't initialize array in struct #809

Open andybalholm opened 5 years ago

andybalholm commented 5 years ago

When there is an initializer list for an array in a struct, the transpiled program fails to compile with a type error. When an array is not in a struct, it transpiles to a slice, but when it's in a struct, it transpiles to an array. I assume this is to maintain the memory layout of the struct (?).

struct aStruct {
    int a[5];
} v = {{1, 2, 3, 4, 5}};

transpiles to

type aStruct struct {
    a [5]int32
}

var v aStruct = aStruct{[]int32{int32(1), int32(2), int32(3), int32(4), int32(5)}}

Which fails to compile because we're trying to assign a slice to an array.

elliotchance commented 5 years ago

I think it's more likely to be a bug with the transpires understanding of what is trying to happen.

If you write them as two separate statements does it produce a correct result?

andybalholm commented 5 years ago

If I separate the declaration of the type from the declaration of the variable from the declaration of the type, I get exactly the same result:

typedef struct {
    int a[5];
} aStruct;
aStruct v = {{1, 2, 3, 4, 5}};
andybalholm commented 5 years ago

If I separate the initialization from the declaration, it isn't valid C, because initializer lists are only allowed in declarations:

typedef struct {
    int a[5];
} aStruct;
aStruct v;

int main() {
    v.a = {1, 2, 3, 4, 5};
}
Konstantin8105 commented 5 years ago

Please try https://github.com/Konstantin8105/c4go

struct aStruct {
    int a[5];
} v = {{1, 2, 3, 4, 5}};
//
//  Package - transpiled by c4go
//
//  If you have found any issues, please raise an issue at:
//  https://github.com/Konstantin8105/c4go/
//

package main

// aStruct - transpiled function from  GOPATH/src/templorary/rot.c:1
type aStruct struct {
    a [5]int32
}

// v - transpiled function from  GOPATH/src/templorary/rot.c:1
var v aStruct = aStruct{[5]int32{1, 2, 3, 4, 5}}