변경 가능한 구조체 API
Coddy의 R 개발자를 위한 C 코스 레슨. 48개 중 25번째.
R 함수는 전달받은 목록을 변경할 수 없으므로, account <- withdraw(account, 2)와 같이 수정된 복사본을 반환하고 다시 할당하는 관용적 방식을 사용하거나, 환경 또는 참조 클래스에서 공유되는 변경 가능한 상태를 유지해야 합니다. C 함수는 구조체 포인터를 받아 ->를 사용해 호출자의 구조체를 제자리에서 갱신할 수 있습니다. 이때 수신 대상은 명시적이며 클래스 시스템은 관여하지 않습니다. 구조체마다 상태를 할당하고, 거부된 작업에서는 상태를 유지하세요.
R
withdraw <- function(account, amount) {
account$balance <- account$balance - amount
account
}
account <- list(balance = 5)
account <- withdraw(account, 2)
print(account$balance)C17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
struct Account {int balance;};
int main(void) {
struct Account a={5};struct Account *p=&a;p->balance-=2;printf("%d\n",a.balance);
return 0;
}
포팅 규칙
구조체 상태를 변경하기 전에 작업을 검증하세요.
챌린지
쉬움Account는 정수 잔액을 포함합니다. withdraw(account,amount)를 구현하세요. 금액이 음수이거나 잔액보다 많으면 상태를 변경하지 않고 false를 반환하고, 그렇지 않으면 잔액에서 금액을 빼고 true를 반환하세요. 0도 유효합니다. 입력은 잔액과 금액이며, 출력은 success:balance입니다. 드라이버는 서로 독립적인 계정과 거부 시 원자성도 검사합니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 공개된 잠금 파일 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){Account a;int amount;if(scanf("%d%d",&a.balance,&amount)!=2)return 1;Account x={4},y={9};if(withdraw(&x,5)||x.balance!=4||withdraw(&x,-1)||x.balance!=4||!withdraw(&x,2)||x.balance!=2||y.balance!=9)return 2;int ok=withdraw(&a,amount);printf("%d:%d\n",ok,a.balance);return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
R 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러