int main ()
{
int next_element = 0;
int size = 10;
int *p_values = new int[ size ];
int val;
cout << "Please enter a number: ";
cin >> val;
while ( val > 0 )
{
if ( size == next_element + 1 )
{
// now all we need to do is implement growArray
// notice that we need to pass in size as a pointer
// since we need to keep track of the size of the array as
// it grows!
p_values = growArray( p_values, & size );
}
p_values[ next_element ] = val;
next_element++;
cout << "Current array values are: " << endl;
printArray( p_values, size, next_element );
cout << "Please enter a number (or 0 to exit): ";
cin >> val;
}
delete [] p_values;
}
void printArray (int *p_values, int size, int elements_set)
{
cout << "The total size of the array is: " << size << endl;
cout << "Number of slots set so far: " << elements_set << endl;
cout << "Values in the array: " << endl;
for ( int i = 0; i < elements_set; ++i )
{
cout << "p_values[" << i << "] = " << p_values[ i ] << endl;
}
}
int *growArray (int* p_values, int *size)
{
*size *= 2;
int *p_new_values = new int[ *size ];
for ( int i = 0; i < *size; ++i )
{
p_new_values[ i ] = p_values[ i ];
}
delete [] p_values;
return p_new_values;
}
내가 구문강조 한데 보면
p_values 요건 메인에서 생성하고 해제하고
다시 메인에서 호출하는 growArray 함수에서 해제시키는데
growArray 함수안에 있는 p_new_values는 생성만 하고 해제를 안하네..
이거 오타 아님?
return 해서 넘기고 메인 마지막에 딜리트 하게 돼있네
바꿔치기 술
ㄴ 동적 할당된 포인터 스왑한거임?? 근데 이렇게 작성하면 나중에 코드 길어지고 복잡하면 관리하기 힘들지 않음?
어떤 점이요?
코드 보면 p_new_values 는 생성만 하고 해제를 안하게 되는데.. 지금은 코드가 짧아서 괜찮겠지만 길어지고 복잡해지면 구별하기 힘들지 않을까요.. new와 delete는 쌍으로 사용하는게 보기도 좋고 편하던데..
그래도 구조를 보면 grow에서 틈틈히 해제가 되고 있다는 건 알 수 있으니까... 코드가 길어지면 변수명도 좀 바꾸고 해야겠지만, 긴 코드를 짜본 적이 없어서 잘 몰라요