주소와 역참조
Coddy의 C# 개발자를 위한 C 코스 레슨. 48개 중 22번째.
C#의 ref는 일반 관리 코드에서 검사되는 참조에 의한 접근을 허용합니다. C는 주소와 역참조를 직접 사용하며, 포인터의 수명이나 대여 규칙을 강제하지 않습니다.
주소를 가져오면 참조된 객체가 살아 있는 동안 간접적으로 값을 업데이트할 수 있습니다. null이 아닌 포인터도 댕글링 포인터일 수 있습니다.
C# 예제
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
static void Set(ref int n){n=5;}
static void Main(){
int n=2;Set(ref n);Console.WriteLine(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 컴파일러