상수 뷰와 변경
Coddy의 Ruby 개발자를 위한 C 코스 레슨. 48개 중 20번째.
Ruby의 freeze는 객체 자체를 동결하므로, 동결된 Array를 참조하는 모든 참조에서 push를 호출하면 FrozenError가 발생합니다. freeze가 없으면 Array를 전달하는 모든 메서드가 해당 배열을 변경할 수 있습니다. C의 const int *는 이 포인터가 가리키는 int를 수정하지 못하게 하지만, 다른 가변 별칭은 여전히 존재할 수 있습니다. 포인터 자체에 const를 적용하는 것은 다른 약속입니다. 읽기 전용 배열 API에는 const 뷰를 사용하세요.
Ruby
values = [2, 3].freeze
puts values.sumC17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
int values[]={2,3};const int *view=values;printf("%d\n",view[0]+view[1]);
return 0;
}
이식 규칙
호출자가 전달한 데이터를 읽기만 하는 API에는 const 포인터를 사용하세요.
챌린지
쉬움입력에는 최대 64개의 정수가 들어갑니다. 배열을 변경하지 않고 const 포인터를 통해 음이 아닌 값의 개수를 세세요. 입력이 비어 있으면 0을 반환합니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 표시된 잠금 상태의 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 values[64];size_t n=0;int value;while(n<64 && scanf("%d",&value)==1)values[n++]=value;int before[64];memcpy(before,values,n*sizeof *values);int count=count_nonnegative(values,n);if(memcmp(before,values,n*sizeof *values)!=0)return 2;printf("%d\n",count);return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Ruby 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러