c로 작성된 코드가 있습니다. main에 int에 대한 포인터가 있고 함수에 전달합니다. 이 함수는 메모리를 할당하고 배열을 채운 다음 반환합니다. 기본적으로 다음과 같습니다.
main()
{
int* array;
function(&array);
}
void function(int** array)
{
int size = 25;
*array = malloc(size);
(*array)[0] = 42;
}
크기는 메인으로 알려져 있지 않습니다. C #에서 어떻게합니까? List로 시도했지만 작동하지 않습니다. 나는 List와 ref List를 모두 시도했으며 둘 다 Index가 범위를 벗어났습니다.
편집하다:
이것은 잘 작동합니다
class Program
{
static void function(List<int> array)
{
array.Add(42);
}
static void Main(string[] args)
{
List<int> array = new List<int>();
function(array);
}
}
그리고 이것도
class Program
{
static void function(out int[] array)
{
array = new int[25];
array[0] = 42;
}
static void Main(string[] args)
{
int[] array;
function(out array);
}
}
그러나 다음은 예외를 throw합니다.
class Program
{
static void function(out List<int> array)
{
array = new List<int>(25);
array[0] = 42;
}
static void Main(string[] args)
{
List<int> array;
function(out array);
}
}
C # 에는 이러한 목적으로 ref 키워드가 있습니다. 어쨌든 배열이 참조 유형이므로이 경우에는 필요하지 않지만 설계 의도를 전달하기 때문에 좋은 생각입니다. 함수에 대한 인수로 out 키워드 를 사용하는 것이 더 좋습니다 . 호출 전에 초기화 할 필요가 없습니다.
이 시도:
class Program
{
static void Main(string[] args)
{
int[] a;
function(out a);
Debug.WriteLine(a.Length);
}
public static void function(out int[] array)
{
array=new int[25];
array[0]=42;
}
}
편집 1- 배열을 반환하는 다른 방법
class Program
{
static void Main(string[] args)
{
int[] a = CreateArray();
Debug.WriteLine(a.Length);
}
public static int[] CreateArray()
{
int[] array=new int[25];
array[0]=42;
return array;
}
}
편집 2- 두 개의 출력 매개 변수가있는 예
class Program
{
static void Main(string[] args)
{
int[] akw, zuk;
function(out akw, out zuk);
Debug.WriteLine(akw.Length);
Debug.WriteLine(zuk.Length);
}
public static void function(out int[] A, out int[] B)
{
A=new int[25];
B=new int[15];
A[0]=42;
B[0]=21;
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다