Menu
CoddyTech

通过指针返回多个结果

Coddy 面向 C# 开发者的 C 课程的第 19 课,共 48 课。

C# 的 out 要求在正常返回前完成赋值。C 的输出指针没有编译器强制执行的等效赋值规则;请明确说明成功和失败状态。

指针参数可以提供额外结果。请说明输出何时有效,以及失败时是否会保留先前状态。

C# 示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
static void Split(int total,out int minutes,out int seconds){minutes=total/60;seconds=total%60;}
static void Main(){
int minutes,seconds;Split(125,out minutes,out seconds);Console.WriteLine(minutes+":"+seconds);
}
}

C# 输出:

2:5

C 示例

#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;
}

C 输出:

2 7
challenge icon

挑战

简单

输入是两个整数。实现 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;}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 C中的所有课

自己练习: C 在线编译器