【发布时间】:2018-02-18 09:19:55
【问题描述】:
我正在学习动态数组,但出现此错误:
数组下标的无效类型'int int'
我不知道我的错误是传递数组还是使用指针。因为如果我在“capt”函数中打印数组,程序会正确运行,但我想学习使用动态数组并将其用作参数。
/*Dynamic Arrays without global variables*/
#include <iostream>
#include <stdlib.h>
using namespace std;
/*Function's prototype*/
void capt(int*, int*); //get variables for ref. and use pointers
void show(int, int); //Only get variabless
int main(){
int nc=0, calf;
capt(&nc,&calf);
show(calf,nc);
system("pause");
return 0;
}
/*Functions*/
void capt(int* nc, int *calf){
cout<<"Digite el numero de calificaciones:"; cin>>*nc;
system("cls");
calf = new int [*nc];
for(int i=0;i<*nc;i++){
cout<<"Ingrese la nota "<<i+1<<": "; cin>>calf[i];
}
}
void show(int calf, int nc){
system("cls");
cout<<".: Notas del usuario :."<<endl;
cout<<"Asignaturas evaluadas: "<<nc<<endl;
for(int i=0;i<nc;i++){
fflush(stdin);
cout<<"Nota "<<i+1<<": "<<*calf[i]<<endl; //<---Error Here
}
}
【问题讨论】:
-
calf = new int [*nc];重新分配 local 指针,它不会修改传入的参数。同样在 C++ 中,您应该更喜欢使用std::vector并通过引用传递而不是传递指针(尽可能) -
没关系,我是新手,因此我不知道 {std::vector},我将阅读此内容以最有效地使用数组。谢谢 =)