WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

cxgo Incorrectly Converts Char Array Initialization, Causing Go Type Mismatch #97

@Yeaseen

Description

@Yeaseen

When transpiling a C struct with a char array (char test_arr[1]) initialized with a character constant, CxGo incorrectly generates Go code that attempts to assign a character ('a') to a [1]byte array, leading to a Go build failure.

Source C code:

#include <stdio.h>
struct todo {
    char test_arr[1]; 
};

char example_fn(struct todo* ex, int index) {
    return ex->test_arr[index];  
}
int main() {
    struct todo example = {'a'};  
    char result = example_fn(&example, 0); 
    printf("Character at index 0: %c\n", result); 
    return 0;
}

C compiler output:

Character at index 0: a

Translated Go code:

package main

import (
	"github.com/gotranspile/cxgo/runtime/stdio"
	"os")
type todo struct {
	test_arr [1]byte
}
func example_fn(ex *todo, index int) int8 {
	return int8(ex.test_arr[index])
}
func main() {
	var (
		example todo = todo{test_arr: [1]byte('a')}
		result  int8 = example_fn(&example, 0)
	)
	stdio.Printf("Character at index 0: %c\n", result)
	os.Exit(0)
}

Go build failure message:

# command-line-arguments
./runner.go:17:41: cannot convert 'a' (untyped rune constant 97) to type [1]byte

What’s Wrong?

  • C allows initializing a char[1] array using {'a'}, treating 'a' as a single element.
  • CxGo translates this incorrectly to [1]byte('a'), which Go does not allow.
  • In Go, a byte array must be initialized using an array literal, such as:
    example := todo{test_arr: [1]byte{'a'}}

Suggested Fix

  • CxGo should translate:
    struct todo example = {'a'};
    to:
    example = todo{test_arr: [1]byte{'a'}}
    instead of [1]byte('a'), ensuring correct initialization.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions