Structs
C Programming Lesson 15 2:24 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Some values belong together.
有些值本来就属于一起。
A point is an x and a y; a rectangle is a width and a height.
一个点是一个 x 和一个 y;一个矩形是宽和高。
You can keep them in separate variables, but three points means six of them, and carrying them separately is how they drift apart.
你当然可以把它们放在各自的变量里, 但三个点就是六个变量,分开搬来搬去,它们迟早会对不上。
A struct fixes that.
结构体解决了这个问题。
You describe one shape with a name, and from then on Point is a type like int.
你把这个形状描述一次并起个名字, 从此 Point 就是一个类型,和 int 一样。
Every Point has an x and a y inside it, and you pass one thing around instead of two.
每个 Point 里面都有一个 x 和一个 y, 你搬来搬去的是一个东西,而不是两个。
Reaching inside is a dot.
要伸手进去,用一个点。
P dot x is the x member of p, and there is nothing special about it after that — you read it and write it exactly like an ordinary variable, in arithmetic, in a condition, anywhere.
p.x 就是 p 的 x 成员,除此之外它没什么特别的—— 你读它、写它,和普通变量完全一样, 放在算式里、放在条件里,哪里都行。
A function can declare a Point, fill in both members, and return the whole thing in one go, which is the first task in this lesson.
一个函数可以声明一个 Point,把两个成员都填好, 然后一次性把整个东西返回出去, 这正是这一课的第一道题。
Now suppose what you hold is not the struct but a pointer to it.
现在假设你手里拿的不是结构体本身,而是指向它的指针。
Then you write an arrow.
那就写一个箭头。
And the arrow is not a second rule to memorise — it is pure shorthand for star p, then dot x: follow the pointer, then take the member.
箭头并不是要你另外背下来的第二条规则—— 它就是 (*p).x 的简写:先跟着指针走,再取成员。
Which tells you why it matters.
这也告诉了你它为什么重要。
Because the pointer leads to the caller's own struct, writing through the arrow changes their data, not a copy of it — and that is the second task.
因为指针通向的是调用者自己的结构体, 透过箭头写进去,改的就是他们的数据,而不是一份副本—— 这正是第二道题。
Put the two tasks side by side and the rule reads itself.
把两道题并排放在一起,规则自己就读出来了。
Make point owns a local Point, builds one and returns it, so every access is a dot.
make_point 拥有一个局部的 Point,把它造出来再返回, 所以里面每一次访问都用点。
Move point takes a pointer, because its whole job is to change something that lives somewhere else, so every access is an arrow.
move_point 接收的是一个指针, 因为它的全部工作就是去改动住在别处的东西, 所以每一次访问都用箭头。
Pick the punctuation by asking one question: do I have the struct, or do I have its address?
选哪个标点,只问一个问题: 我手里拿的是这个结构体,还是它的地址?
Four things to take with you.
带走四点。
One: a struct groups related values into one thing, and typedef gives that thing a short name.
第一:结构体把相关的值组合成一个东西, 而 typedef 给这个东西起了个短名字。
Two: on a struct value, reach a member with a dot.
第二:拿到的是结构体的值,就用点访问成员。
Three: when you hold a pointer, use the arrow instead.
第三:拿到的是指针,就改用箭头。
Four: the arrow is shorthand for star p, then dot.
第四:箭头是 (*p) 再加点的简写。
Now do the three tasks — the third one reads members through a const pointer.
现在去做那三道题——第三题是透过一个 const 指针读取成员。