[英]C++: Variable Size 2D array as an argument to a function
我需要解決此問題的最簡單方法:當我嘗試編譯以下代碼時,它說您不能在函數主體之外使用nR,在函數的聲明中傳遞雙指針不起作用,因為它不允許我投放:
A(int nT, int nR, int arr[][nR]){
for(int i = 0; i< nT; i++){
for(int j = 0; j< nR; j++){
cout<< arr[i][j] << endl;}
}
}
int main(){
int requests[2][3] = { { 1, 2, 3} , { 4, 32, 6 } };
A(2,3, requests );
return 0;
}
如果將函數設為模板,則可以執行以下操作:
template<std::size_t N, std::size_t M>
A(int (&arr)[N][M]){
for(int i = 0; i< N; i++){
for(int j = 0; j < M; j++){
cout<< arr[i][j] << endl;
}
}
}
然后在主要:
int main(){
int requests[2][3] = { { 1, 2, 3} , { 4, 32, 6 } };
A(requests);
return 0;
}
C ++(和C)數組不可調整大小,並且不包含大小信息。
為此,您應該使用std::vector
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.