为什么该函数不会获得动态数组?(我正在使用指针和参考)

Why the function do not get the dynamic array? (I am using pointers and references)

本文关键字:指针 参考 函数 数组 动态 为什么      更新时间:2023-10-16

我正在学习有关动态数组的知识,我会得到此错误:

阵列下标的无效类型'int'

我不知道我的错误是通过数组还是使用指针。因为如果我在"上尉"函数中打印数组,程序可以正确运行,但我想学习使用动态数组并将其像参数一样使用。

/*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
    }
}

您将其弄乱。这里

void show(int calf, int nc){

然后在这里

cout<<"Nota "<<i+1<<": "<<*calf[i]<<endl; //<---Error Here

您在第一个摘要calf中看到的是整数,然后在第二个摘要上,您使用数组索引访问它(您还具有不必要的 * Derference操作(。

另外:

calf = new int [*nc];

使局部变量calf指向新的内存地址,它不会影响原始变量;即使它确实做到了原始变量calfint,所以您再次在这里弄乱。


我认为您所追求的是这样的(尝试阅读C 中的指针的内容,以了解我所做的更改(:

#include <iostream>
#include <stdlib.h>
using namespace std;

/*Function's prototype*/
void capt(int* nc, int *&calf); //get variables for ref. and use pointers
void show(int*, int);   //Only get variabless
int main(){
    int nc=0;
    int *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;  
    }
}