地址与解引用
Coddy 面向 Python 开发者的 C 课程的第 22 课,共 48 课。
Python 提供引用,但不提供通用地址运算。在 C 中,&object 获取地址,*pointer 访问指针指向的对象。只能解引用指向有效且仍然存活的正确类型对象的指针。空指针和悬空指针不是普通的空值。
Python
box=[2]
alias=box
alias[0]=5
print(box[0])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;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 C中的所有课
自己练习: C 在线编译器