We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Initializers

So now you're probably wondering: "Hey TJ, so... how do we actually make an instance of a struct"? You may have noticed in the previous lesson all we did was define the struct type.

Unfortunately, there are a few different ways to initialize a struct, I'll give you an example of each using this struct:

struct City {
  char *name;
  int lat;
  int lon;
};

Zero Initializer

int main() {
  struct City c = {0};
}

This sets all the fields to 0 values.

Positional Initializer

int main() {
  struct City c = {"San Francisco", 37, -122};
}

Designated Initializer

This is my (generally) preferred way to initialize a struct. Why?

  • It's easier to read (has the field names)
  • If the fields change, you don't have to worry about breaking the ordering
int main() {
  struct City c = {
    .name = "San Francisco",
    .lat = 37,
    .lon = -122
  };
}

Remember, it's .name not name. If this trips you up, just remember it's .name and not name because that's how you access the field, e.g. c.name.

Accessing Fields

Accessing a field in a struct is done using the . operator. For example:

struct City c;
c.lat = 41; // Set the latitude
printf("Latitude: %d", c.lat); // Print the latitude

There's another way to do this for pointers that we'll get to later.

Assignment

Complete the new_coord function. It accepts 3 integers and returns a Coordinate.

Use the "designated initializer" syntax... because I said so.

Tip

The easiest way to return a struct is to initialize it in a variable first. If you want to skip the variable assignment, you can write something like this:

struct City new_city(char *name, int lat, int lon) {
    return (struct City){.name = name, .lat = lat, .lon = lon};
}