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.0040 sec