知识点10:结构(structures)

How do we create different data types? We can do so by using structures.

知识点10:结构(structures)_第1张图片

So here's an example of a very simple structure. This is what the syntax would look like to create a structure for a car.

知识点10:结构(structures)_第2张图片

After we finish defining the structure, we need to put a semicolon at the end.

It's a very common syntactical mistake, because with a function, for example, you would just have open curly brace, close curly brace. You don't put a semicolon at the end of a function definition. This looks like a function definition, but it's not, and so the semicolon there is just a reminder that you need to put it there, because the compiler will otherwise not know what to do with it.

知识点10:结构(structures)_第3张图片

So for example, let's say I've declared my structure data type somewhere
at the top of my program, or perhaps in a dot h file that I've pound included.
If I then want to create a new variable of that data type, I can say:

知识点10:结构(structures)_第4张图片

The data type here is struct car, the name of the variable is my car, and then I can use the dot operator to access the various fields of my car.

知识点10:结构(structures)_第5张图片

If we only have a pointer to the structure, we can't just say pointer dot field name and get what we're looking for.

There's the extra step of dereferencing.

知识点10:结构(structures)_第6张图片

So let's say that instead of the previous -- just like the previous example, instead of declaring it on the stack, struct car, my car, semicolon, I say struct car, star, a pointer to a struct car called my car, equals malloc size of struct car.

You don't necessarily only need to use size of, width, int, or char, or any of the built-in data types.

The compiler is smart enough to figure out how many bytes are required by your new structure.

So I malloc myself a unit of memory big enough to hold a struct car, and I get a pointer back to that block of memory, and that pointer is assigned to my car.

Now, if I want to access the fields of my car:

知识点10:结构(structures)_第7张图片

That's kind of annoying, though, right?

C programmers love shorter ways to do things, there is a shorter way to do this.

There is another operator called arrow, which makes this process a lot easier.

知识点10:结构(structures)_第8张图片

The way arrow works is it first dereferences the pointer on the left side of the operator, and then, after having dereferenced the pointer on the left, it accesses the field on the right.

what we can instead do is this:

知识点10:结构(structures)_第9张图片

Again, what's happening here?

First, I'm dereferencing my car. Which again, is a pointer here. Then, after having dereferenced my car, I can then access the fields year, plate, and odometer just as I could before having first used star to dereference my car, and dot to access the field.

The End

你可能感兴趣的:(知识点10:结构(structures))