다음 코드 조각이 있습니다.이 코드는 배열 크기 조정 함수의 구현입니다. 올바른 것 같다,하지만 난 다음과 같은 오류를 얻을 프로그램을 컴파일 할 때 :int 포인터로 인해 오류가 발생합니다.
이int N=5;
void resize(int *&arr, int N, int newCap, int initial=0) { // line 7
N = newCap;
int *tmp = new int[ newCap ];
for(int i=0; i<N; ++i) {
tmp[ i ] = arr[ i ];
}
if(newCap > N) {
for(int i=N; i<newCap; ++i) {
tmp[ i ] = initial;
}
}
arr = new int[ newCap ];
for(int i=0; i<newCap; ++i) {
arr[ i ] = tmp[ i ];
}
}
void print(int *arr, int N) {
for(int i=0; i<N; ++i) {
cout << arr[ i ];
if(i != N-1) cout << " ";
}
}
int main() {
int arr[] = { 1, 2, 3, 4, 5 };
print(arr, N);
resize(arr, N, 5, 6); // line 37
print(arr, N);
resize(arr, N, 10, 1); // line 39
print(arr, N);
resize(arr, N, 3); // line 41
print (arr, N);
return 0;
}
이 사람이 나를 도울 수 :
여기g++ -Wall -o "resizing_arrays" "resizing_arrays.cpp" (in directory: /home/aristofanis/Desktop/coursera-impl)
resizing_arrays.cpp: In function ‘int main()’:
resizing_arrays.cpp:37: error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
resizing_arrays.cpp:7: error: in passing argument 1 of ‘void resize(int*&, int, int, int)’
resizing_arrays.cpp:39: error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
resizing_arrays.cpp:7: error: in passing argument 1 of ‘void resize(int*&, int, int, int)’
resizing_arrays.cpp:41: error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
resizing_arrays.cpp:7: error: in passing argument 1 of ‘void resize(int*&, int, int, int)’
Compilation failed.
코드인가? 미리 감사드립니다.
이어야한다. void resize (int * & arr' here '& ' –
@IonutHulub - 포인터 인수가 가리키는 배열의 크기를 변경하는 함수의 목적을 무효화 할 것입니다. –
'* & arr' 같은 것이 없습니다. 당신은 그것이라고 생각합니까? arr은 포인터이므로 호출 할 수는 없습니다. 그리고 가능하다해도 참조를 위해 하나의 원인을 취소하고 참조를 위해 하나를 사용하십시오. –