주소와 역참조
Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 22번째.
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 n=2;int& alias=n;alias=5;std::cout<<n<<"\n";
}
C++ 출력:
5C 예제
#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 n=2;int *p=&n;*p=5;printf("%d\n",n);
return 0;
}
C 출력:
5챌린지
쉬움입력은 정수 두 개입니다. 유효한 포인터를 사용해 swap(a,b)를 구현하세요. 또한 값이 바뀌지 않도록 a==b인 경우도 처리하세요. 잠긴 main은 바뀐 쌍을 출력하기 전에 해당 별칭 경우를 확인합니다.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 이를 직접 호출하는 잠긴 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;if(scanf("%d%d",&a,&b)!=2)return 1;int x=5;swap(&x,&x);if(x!=5)return 2;swap(&a,&b);printf("%d:%d\n",a,b);return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러