Menu
CoddyTech

포인터로 여러 결과 반환하기

Coddy의 Dart 개발자를 위한 C 코스 레슨. 48개 중 19번째.

Dart 3은 (int, int)와 같은 레코드로 여러 값을 반환하고, 호출자는 패턴을 사용해 값을 분해합니다. C에는 레코드나 튜플이 없습니다. 함수는 보통 포인터 매개변수를 통해 추가 결과를 기록하고, 호출자는 자신의 변수 주소를 전달합니다. 출력 포인터에는 유효성 및 실패 상태 규칙을 명시해야 합니다.

포인터 매개변수로 추가 결과를 전달할 수 있습니다. 출력값이 언제 유효한지, 실패 시 이전 상태가 유지되는지를 문서화하세요. 값들이 서로 연관되어 있다면 작은 구조체를 반환하는 것이 Dart 레코드에 가장 가까운 C 방식입니다.

Dart 예제

(int, int) bounds(int a, int b) => a < b ? (a, b) : (b, a);

void main() {
  var (low, high) = bounds(7, 2);
  print('$low $high');
}

Dart 출력:

2 7

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를 출력합니다.

잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 표시된 잠금 상태의 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;}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Dart 개발자를 위한 C의 모든 레슨

직접 연습해 보세요: 온라인 C 컴파일러