포인터로 여러 결과 반환하기
Coddy의 Luau 개발자를 위한 C 코스 레슨. 48개 중 19번째.
Luau 함수는 여러 값을 반환할 수 있으며, 호출자는 local a, b = f()를 사용해 값을 받습니다. C 함수는 값 하나를 반환합니다. 구조체를 반환하거나 출력 포인터와 상태 결과를 함께 사용하세요. 호출이 실패했을 때 출력값에 어떤 일이 일어나는지 명시하세요. 호출자가 부분적으로 갱신된 값을 보지 않도록 사전 조건을 검증한 뒤에만 결과를 쓰세요.
Luau
local function bounds(a, b)
return math.min(a, b), math.max(a, b)
end
local low, high = bounds(7, 2)
print(`{low} {high}`)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를 출력합니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 이를 직접 호출하는 잠긴 main.c에 표시된 공개 API 선언과 호환되도록 유지하세요. 다른 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;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Luau 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러