通过指针返回多个结果
Coddy 面向 GDScript 开发者的 C 课程的第 19 课,共 48 课。
GDScript 没有元组,也没有用于值类型的输出参数,因此需要返回两个结果的函数会返回一个 Array 或 Dictionary,也可以通过引用填充调用方传入的值。C 可以返回结构体,也可以使用输出指针和状态结果。说明调用失败时输出会发生什么。只有在验证前置条件后才写入结果,这样调用方就不会看到部分更新。
GDScript
extends Node
func bounds(a: int, b: int) -> Array:
return [mini(a, b), maxi(a, b)]
func _ready():
var r := bounds(7, 2)
print(r[0], " ", r[1])
C17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static void bounds(int a,int b,int *low,int *high){*low=a<b?a:b;*high=a>b?a:b;}
int main(void) {
int low=0,high=0;bounds(7,2,&low,&high);printf("%d %d\n",low,high);
return 0;
}
移植规则
说明函数会写入哪些由调用方拥有的输出位置。
挑战
简单输入是两个整数。实现 bounds(a,b,low,high),将较小值和较大值分别写入有效且不重复的输出指针。驱动程序会打印 low:high。
编辑未锁定的源文件和头文件。保持已声明的公共 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,low=0,high=0;if(scanf("%d%d",&a,&b)!=2)return 1;bounds(a,b,&low,&high);printf("%d:%d\n",low,high);return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 C中的所有课
自己练习: C 在线编译器