简体   繁体   English

传递指向 int 数组的指针,作为参数 C++

[英]Passing a pointer to an int array, as an argument C++

I know even if i pass an array by typing arrayname as argument (ex: getArrayInput(arrayexample); ), it will copy only the adress value of first element not entire array,still i wonder why these code gives error.我知道即使我通过输入 arrayname 作为参数传递一个数组(例如:getArrayInput(arrayexample);),它也只会复制第一个元素的地址值而不是整个数组,我仍然想知道为什么这些代码会出错。 I know this not the way how it should implemented but i want to understand this error.我知道这不是它应该如何实现的方式,但我想了解这个错误。

main.cpp|13|error: cannot convert 'int*' to 'int**' for argument '1' to 'void getArrayInput(int**)'| 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;
        }
    }
}

It is because这是因为

int * 

and

int[] 

are both of type都是类型

int *

therefore, you are here asking for a因此,你在这里要求一个

int **.

try replacing尝试更换

void getArrayInput(int * []) by     void getArrayInput(int *)

In C, arrays decay in to pointers.在 C 中,数组衰减为指针。 In some cases, they are interchangable.在某些情况下,它们可以互换。

ptScores is of type int* (pointer to int). ptScoresint*类型(指向 int 的指针)。 getArrayInput expects an int*[] (array of pointers to int). getArrayInput需要一个int*[] (指向 int 的指针数组)。 int*[] decays in to int** (pointer to pointer to int). int*[]衰减为int** (指向int**指针的指针)。

The error says you're giving an int* (ptScores) to something that expects an int** (getArrayInput).该错误表示您正在为需要int** (getArrayInput) 的内容提供int* (ptScores)。


How do you fix this?你如何解决这个问题? Take an int* .取一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM