리스트와 안전한 갱신
Coddy의 C 개발자를 위한 C# 코스 레슨. 48개 중 16번째.
C에는 크기를 늘릴 수 있는 배열이 없습니다. 포인터, 개수, 용량을 유지하고 저장 공간이 가득 차면 realloc을 호출합니다. realloc은 데이터를 이동할 수 있으며, 그러면 데이터 내부를 가리키던 모든 기존 포인터가 댕글링 포인터가 됩니다. C#의 List<T>는 이 관리를 대신해 줍니다. Add는 저장 공간을 늘리고 Count는 길이를 추적합니다. 리스트 변수를 할당하면 참조만 복사되며, 이는 C의 malloc 블록을 가리키는 포인터를 복사하는 것과 비슷하므로 두 이름 모두 같은 요소를 가리킵니다. C에서 두 번째 블록을 할당하고 memcpy를 사용할 부분에는 new List<int>(values)를 사용하세요.
List<T>는 배열과 달리 크기를 조정할 수 있습니다. Count는 요소의 개수를 반환하고, Add는 값을 추가합니다. 다른 리스트에서 새 List<int>를 만들면 정수 요소가 복사되지만, 할당은 참조만 복사합니다. 잠긴 드라이버는 원본이 변경되지 않는지 확인합니다.
C 참고 코드
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t count = 1, capacity = 1;
int *values = malloc(capacity * sizeof *values);
if (values == NULL) return 1;
values[0] = 2;
if (count == capacity) {
capacity *= 2;
int *grown = realloc(values, capacity * sizeof *values);
if (grown == NULL) { free(values); return 1; }
values = grown;
}
values[count++] = 5;
printf("%zu\n", count);
free(values);
return 0;
}
Main 안의 C# 문장
var values = new List<int> { 2 };
values.Add(5);
Console.WriteLine(values.Count);이는 핵심 내용에 집중한 교육용 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장을 보여 줍니다.
참조 출력:
2C# 출력:
2챌린지
쉬움정수 목록이 있는 줄과 추가 정수가 있는 줄을 읽으세요. 추가 정수를 뒤에 붙인 새 목록을 반환하세요. 전달된 목록은 수정하지 마세요. 드라이버는 values: 뒤에 쉼표로 구분된 값들을 출력합니다.
잠금 해제된 C# 파일을 편집하세요. 잠긴 상태로 표시된 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인하고, 마지막에 줄바꿈을 하나 넣어 결과를 출력합니다. 선언된 API를 그대로 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 하지 마세요.
직접 해보기
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = new List<int>(Ints(input[0])); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine("values:" + string.Join(",", result));
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러