Structs in Cilk

Based on the provided input, here is the translation of the Go code example to the target language “cilk”.

Our first program will define and use structs, demonstrating their usefulness in grouping data together to form records.

#include <cilk/cilk.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct {
    char* name;
    int age;
} person;

person* newPerson(char* name) {
    person *p = (person *)malloc(sizeof(person));
    p->name = strdup(name);
    p->age = 42;
    return p;
}

int main() {
    // This syntax creates a new struct.
    person p1 = {"Bob", 20};
    printf("{%s %d}\n", p1.name, p1.age);

    // Name the fields when initializing a struct.
    person p2 = {.name="Alice", .age=30};
    printf("{%s %d}\n", p2.name, p2.age);

    // Omitted fields will be zero-valued.
    person p3 = {.name="Fred"};
    printf("{%s %d}\n", p3.name, p3.age);

    // An `&` prefix yields a pointer to the struct.
    person *p4 = &(person){.name="Ann", .age=40};
    printf("&{%s %d}\n", p4->name, p4->age);

    // Encapsulate new struct creation in constructor functions
    person *p5 = newPerson("Jon");
    printf("&{%s %d}\n", p5->name, p5->age);

    // Access struct fields with a dot.
    person s = {.name="Sean", .age=50};
    printf("%s\n", s.name);
    
    // Use dots with struct pointers - they are automatically dereferenced.
    person *sp = &s;
    printf("%d\n", sp->age);

    // Structs are mutable.
    sp->age = 51;
    printf("%d\n", sp->age);

    // Anonymous struct type.
    struct {
        char* name;
        int isGood;
    } dog = {"Rex", 1};

    printf("{%s %d}\n", dog.name, dog.isGood);

    // Clean up
    free(p5->name);
    free(p5);
    free(p4->name);

    return 0;
}

To run the program, save the code in a file called structs.c and compile it with a Cilk-capable compiler.

$ cilkc structs.c -o structs
$ ./structs
{Bob 20}
{Alice 30}
{Fred 0}
&{Ann 40}
&{Jon 42}
Sean
50
51
{Rex 1}

In this program, we demonstrated defining a struct type, creating new struct instances, using pointers, and fields access, encapsulating struct creation in constructor functions, and handling anonymous structs.

Now that we can define and use structs, let’s learn more about the language.