Jinan Dangor
Jinan Dangor

Reputation: 142

Initialising a struct inside an array

Recently, I attempted the following, as a shorthand for initialising a new structure and making it the first element of an array:

#include <stdio.h>

#define MAX_CARS 100

typedef struct car {
    int wheels;
    int cylinders;
    int maxSpeed;
    int canOffroad;
} Car;

int main(void) {
    Car all_cars[MAX_CARS];
    // This is nice, I would like to do something equivalent to this
    all_cars[0] = {.wheels = 4,
                   .cylinders = 8,
                   .maxSpeed = 120,
                   .canOffroad = 0};

    return 0;
}

This, however, throws a compiler error, saying that it expects an expression before the '{'.

Now, at first I thought I might have mis-remembered initialising structs, but this works:

#include <stdio.h>

#define MAX_CARS 100

typedef struct car {
    int wheels;
    int cylinders;
    int maxSpeed;
    int canOffroad;
} Car;

int main(void) {
    Car all_cars[MAX_CARS];
    // This is ok, but introduces a (potentially) unnecessary variable
    Car new_car = {.wheels = 4,
                   .cylinders = 8,
                   .maxSpeed = 120,
                   .canOffroad = 0};
    all_cars[0] = new_car;

    return 0;
}

So the problem is clearly in initialising this structure as an element of an array instead of as a variable.

Is there syntax which allows for initialising structs like this, or am I stuck initialising a new struct variable every time I want to add one to an array?

Upvotes: 0

Views: 64

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

The problem is that you attempt to initialize the element in the array, which is only possible when you define the array.

Initialization is only possible with definition.

You can however use compound literals to create a temporary structure object that is then copied into the array element:

all_cars[0] = (Car) {.wheels = 4,
                     .cylinders = 8,
                     .maxSpeed = 120,
                     .canOffroad = 0};

Upvotes: 3

Related Questions