How do we create different data types? We can do so by using structures.
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.
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.
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:
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.
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.
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:
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.
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:
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
网友评论