U E D R , A S I H C RSS

이승한/질문

승한이 질문 페이

~cpp 
void Test(int * Ascores)
{
	cout << "in function : ";
	cout << sizeof(Ascores) << " " << sizeof(Ascores[0]) << endl;
}

void main()
{
	int scores[4]={1,2,3,4};
	cout<<"in main : ";
	cout << sizeof(scores) << " " << sizeof(scores[0]) << endl;
	Test(scores);
}
strlen 처럼 int 형 배열의 길이를 구하는 함수를 짜던중 이해 안되는 부분.
메인에서 들어간 sizeof(scores)는 배열 전체 크기를 리턴하는 반면에 함수에 들어간 sizeof(scores)는 int* 형의 크기를 리턴한다.
메인에서 처럼 전체 배열크기만큼 리턴시킬수 있는 방법은 없나요??

다른 질문.
참조를 이용해 배열을 함수에 넘길수는 없는건가요?? 배열은 잘 넘어가 않네요;;
vs에서 타이핑하는 방식이외에 자동으로 함수를 생성해주는 바법사를 이용해 firend 함수를 생성할수는 없나요??

강희경의 나름대로의 답변

아마 승한이가 원하는 답은 아니겠만 한번 적어본다. 금 함수에 전달하는 것은 인트형의 포인터이기 때문에 함수는 금 받은 것이 숫자인 배열인 알 수 가 없. 게다가 주소를 참조하게 되서 함수 안에서 그 값을 변경해주면 원본 값도 변하게 되고. 그래서 나는 함수 안에 멤버 변수를 만들어서 전달 값을 복사해서 쓰거든. 보통 전달인수를 받을 때 컴파일러에서 그 원본 값을 쓰 않고 복사값을 사용하는 건 알? 그 작업을 프로그래머가 해주는 것이. 밑은 여태 말한대로 구현하고 간단하게 테스트한 소스야.
~cpp 
#include<iostream>
using namespace std;

void Test(int *aArray, int aLength) 
{	
	int *copyArray = new int[aLength];//전달 배열과 같은 크기의 새로운 배열 생성
	for(int index = 0; index < aLength; index++)
		copyArray[index] = aArray[index];//값 복사
	cout << "in function : "; 
    cout << sizeof(copyArray[0])*aLength << " " << sizeof(copyArray[0]) << endl;
	
	//여기부터는 테스트를 위해 임의로 만든 코드!
	
	cout << "\n변경 전의 copyArray : ";//변경 전의 값은 전달 배열과 같다
	for(index = 0; index < aLength; index++)
		cout << copyArray[index] << " ";
	cout << endl;
	for(index = 0; index < aLength; index++)//copyArray의 모든 값을 0으로 초기화
		copyArray[index] = 0;
	cout << "변경 후의 copyArray : ";
	for(index = 0; index < aLength; index++)
		cout << copyArray[index] << " ";
	cout << endl;
	
	delete []copyArray;//메모리 해제는 필수!!!
} 
 
void main() 
{ 
	int arrayLength;
    int scores[4]={1,2,3,4}; 
    cout<<"in main : "; 
    cout << sizeof(scores) << " " << sizeof(scores[0]) << endl; 
    arrayLength = sizeof(scores)/sizeof(scores[0]);
	Test(scores, arrayLength);
	
	//검사!!
	cout << "\n함수에 전달된 값이 변해도 scores의 값은 변하 않는다.\nscores: ";
	for(int index = 0; index < arrayLength; index++)
		cout << scores[index] << " ";
	cout << endl;
}


Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:30:31
Processing time 0.0130 sec