Blaise Arrays

I added support for arrays inside of Blaise. Instead of modifying the grammar I modified the compiler to look for foreign function interface constructs. Since Blaise compiles to C I have to make sure all Blaise code compiles to compliable C. Supporting arrays in Blaise wasn’t too hard, but there was one obstacle I didn’t expect to run into. Due to little experience with C I found out  that creating arrays dynamically in C isn’t as easy as I first thought.

For example, the following createArray function does not work in C:

void* createArray(int length, void* initialValueForEachElement){
    void* arr[length];
    int i;
    for(i = 0;i< length; i++){
        arr[i] = initialValueForEachElement;
    }
}

I did come up with a solution to my problem. Anytime I call the createArray function I know the length of an array specified by the Blaise programmer so I declare the array before the function call and pass it in.

void* createArray(void* arr[], int length, void* initialValueForEachElement){
    int i;
    for(i = 0;i< length; i++){
        arr[i] = initialValueForEachElement;
    }
}
int main(){
    int length = 5;
    void* arr[length]; createArray(arr, length, 3); // arr was successfully created
}

After talking to a postdoc I discovered an even better solution so I don’t have to declare the array before the call.

void **Array_make(int size) {
    void **arr = malloc(size*sizeof(void *));
    return arr;
}

Leave a Reply