地址与解引用
Coddy 面向 Lua 开发者的 C 课程的第 22 课,共 48 课。
Lua 表变量保存的是引用:两个名称可以指向同一个表,但 Lua 没有取地址运算符,也不支持指针算术,而且垃圾回收器会让被引用的表保持存活。在 C 中,&object 用于获取地址,*pointer 用于访问指针所指向的对象。只有当指针有效、指向存活且类型正确的对象时,才能解引用。空指针和悬空指针不是像 nil 那样普通的空值:在 Lua 中对 nil 进行索引会引发错误,而在 C 中解引用无效指针的行为未定义。
Lua
local box = {2}
local alias = box
alias[1] = 5
print(box[1])C17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
int n=2;int *p=&n;*p=5;printf("%d\n",n);
return 0;
}
移植规则
只有当指针指向的目标有效且仍然存活时,才能解引用。
挑战
简单输入是两个整数。使用有效指针实现 swap(a,b)。同时支持 a==b,且不改变值。锁定的 main 会在打印交换后的数对之前检查别名情况。
编辑未锁定的源文件和头文件。保持声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 main。除非任务明确检查范围,否则所有数字任务数据都足够小,不会溢出。只打印指定的输出;如有显示,驱动程序会负责解析输入和生成输出。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int a,b;if(scanf("%d%d",&a,&b)!=2)return 1;int x=5;swap(&x,&x);if(x!=5)return 2;swap(&a,&b);printf("%d:%d\n",a,b);return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Lua 开发者的 C中的所有课
自己练习: C 在线编译器