[英]Passing a pointer to an int array, as an argument C++
我知道即使我通過輸入 arrayname 作為參數傳遞一個數組(例如:getArrayInput(arrayexample);),它也只會復制第一個元素的地址值而不是整個數組,我仍然想知道為什么這些代碼會出錯。 我知道這不是它應該如何實現的方式,但我想了解這個錯誤。
main.cpp|13|錯誤:無法將參數“1”的“int*”轉換為“int**”到“void getArrayInput(int**)”|
#include <iostream>
using namespace std;
void getArrayInput(int * []);
int main()
{
cout<<"Enter scores on by one.." << endl;
cout<<"To terminate input enter -1"<<endl;
int listof[10]={};
int *ptScores =listof;
getArrayInput(ptScores);
return 0;
}
void getArrayInput(int * []){
for(int i=0;i<10;i++){
cin>>*(pt+i);
if(*(pt+i))=-1){
break;
}
else{
cout<<"Enter next.."<<endl;
}
}
}
這是因為
int *
和
int[]
都是類型
int *
因此,你在這里要求一個
int **.
嘗試更換
void getArrayInput(int * []) by void getArrayInput(int *)
在 C 中,數組衰減為指針。 在某些情況下,它們可以互換。
ptScores
是int*
類型(指向 int 的指針)。 getArrayInput
需要一個int*[]
(指向 int 的指針數組)。 int*[]
衰減為int**
(指向int**
指針的指針)。
該錯誤表示您正在為需要int**
(getArrayInput) 的內容提供int*
(ptScores)。
你如何解決這個問題? 取一個int*
。
void getArrayInput(int* pt){
for(int i=0;i<10;i++){
cin>>pt[i];
if(pt[i]=-1){
break;
}
else{
cout<<"Enter next.."<<endl;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.