【问题标题】:Why the function do not get the dynamic array? (I am using pointers and references)为什么函数没有得到动态数组? (我正在使用指针和引用)
【发布时间】: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},我将阅读此内容以最有效地使用数组。谢谢 =)

标签: c++ arrays dynamic


【解决方案1】:

你搞砸了。这里

void show(int calf, int nc){

那么这里

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

正如您在第一个 sn-p 中看到的,calf 是一个整数,然后在第二个 sn-p 中您正在使用数组索引访问它(您还有一个不必要的 * 取消引用操作)。

还有这个:

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;  
    }
}

【讨论】:

  • 哦,好的,我明白了,我要阅读有关 {reference to pointers} 我的错误是理论上的,我不知道这个话题。感谢程序运行正确=)。
  • @JavierGámezBojórquez 或者首先了解什么是 C++ 中的 reference 类型,然后引用指针。祝你好运。
猜你喜欢
  • 2021-09-17
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2019-10-25
  • 2014-03-30
  • 1970-01-01
相关资源
最近更新 更多