

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Structs
incomplete
2: Initializers
incomplete
3: Scaling Coordinate
incomplete
4: Typedef
incomplete
5: Sizeof
incomplete
6: Struct Padding
incomplete
This lesson's interactive features are locked, please to keep using them
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;
};
int main() {
struct City c = {0};
}
This sets all the fields to 0 values.
int main() {
struct City c = {"San Francisco", 37, -122};
}
This is my (generally) preferred way to initialize a struct. Why?
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 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.
Complete the new_coord function. It accepts 3 integers and returns a Coordinate.
Use the "designated initializer" syntax... because I said so.
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};
}