포인터 연산과 경계
Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 23번째.
C와 C++의 원시 포인터 산술에도 비슷한 배열 경계 제한이 있습니다. C에는 순회를 묶어 제공할 수 있는 표준 반복자와 범위가 없습니다. 배열의 끝을 한 칸 지난 포인터도 역참조해서는 안 됩니다.
포인터 산술은 배열 객체 내에서 요소 단위로 이동합니다. 배열의 끝을 한 칸 지난 포인터는 만들 수 있지만 역참조해서는 안 됩니다.
C++ 예제
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
int main(){
int a[]={2,4,6};int* p=a+1;std::cout<<p[0]+p[1]<<"\n";
}
C++ 출력:
10C 예제
#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 a[]={2,4,6};int *p=a+1;printf("%d\n",p[0]+p[1]);
return 0;
}
C 출력:
10챌린지
쉬움입력은 최대 64개의 정수로 이루어집니다. 첫 번째 요소 뒤에 있는 모든 요소를 더하세요. 포인터와 길이 계약을 따르세요. 입력이 비어 있거나 요소가 하나뿐이면 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;printf("%d\n",tail_sum(values,n));return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러