Array: pass by value vs pass by reference

static void ChangeArray1(int[] arr) // copy of reference가 전달
{
arr[0] = 888; // 원본 배열의 첫번째 값은 888로 변경
for (int i = 0; i < arr.Length; i++ )
Console.WriteLine(“inside arr[{0}]={1}”, i, arr[i]);

arr = new int[5] { -3, -1, -2, -3, -4 }; // local 변수 재지정
for (int i = 0; i < arr.Length; i++ )
Console.WriteLine(“inside2 arr[{0}]={1}”, i, arr[i]);
}

static void ChangeArray2(ref int[] arr)
{
arr[0] = 888; // 원본 배열의 첫번째 값은 888로 변경
for (int i = 0; i < arr.Length; i++ )
Console.WriteLine(“inside arr[{0}]={1}”, i, arr[i]);

arr = new int[5] { -3, -1, -2, -3, -4 }; // 원본 배열이 변경
for (int i = 0; i < arr.Length; i++ )
Console.WriteLine(“inside2 arr[{0}]={1}”, i, arr[i]);
}

static void Main()
{
int[] myArray = { 1, 4, 5 };
Console.WriteLine(“myArray[0]={0}”, myArray[0]);
ChangeArray1(myArray);
for (int j = 0; j < myArray.Length; j++ )
Console.WriteLine(“myArray[{0}]={1}”, j, myArray[j]);

myArray = new int[3] { 1, 4, 5 };
Console.WriteLine(“myArray[0]={0}”, myArray[0]);
ChangeArray2(ref myArray);
for (int j = 0; j < myArray.Length; j++ )
Console.WriteLine(“myArray[{0}]={1}”, j, myArray[j]);
}



출력결과:
myArray[0]=1
inside arr[0]=888
inside arr[1]=4
inside
arr[2]=5
inside2 arr[0]=-3
inside2 arr[1]=-1
inside2 arr[2]=-2
inside2 arr[3]=-3
inside2
arr[4]=-4
myArray[0]=888
myArray[1]=4
myArray[2]=5

myArray[0]=1
inside
arr[0]=888
inside arr[1]=4
inside arr[2]=5
inside2 arr[0]=-3
inside2
arr[1]=-1
inside2 arr[2]=-2
inside2 arr[3]=-3
inside2
arr[4]=-4
myArray[0]=-3
myArray[1]=-1
myArray[2]=-2
myArray[3]=-3
myArray[4]=-4

Leave a Reply

Your email address will not be published. Required fields are marked *