为什么该函数不会获得动态数组?(我正在使用指针和参考)
Why the function do not get the dynamic array? (I am using pointers and references)
我正在学习有关动态数组的知识,我会得到此错误:
阵列下标的无效类型'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
指向新的内存地址,它不会影响原始变量;即使它确实做到了原始变量calf
是int
,所以您再次在这里弄乱。
我认为您所追求的是这样的(尝试阅读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;
}
}
相关文章:
- 我可以有一个 ELI5 作为参考和指针以及何时使用它们吗?
- 类的方法和对象。参考?智能指针?简单的初始化?
- 我正在学习C++,我不能使用指针访问参考吗?(举个例子)
- 使用指针向量到参考向量是非法的吗?
- 函数参数绑定通过参考与传递指针传递数组的规则
- 参考参考static_cast的成本和指向指针static_cast的指针
- 函数采用原始指针试图通过错误msg中概述的参考来接受指针
- 为什么即使传递给函数作为参考,指针也未被分配
- 为什么通用参考概念不适用于函数指针的地图插入
- 是指代指针正交的参考文献
- 超载函数既不按值,也不是通过参考来对象,而是将撤销的指针换成对象
- 从参考中获取的指针可以在定义明确的C 中取无效
- 指针与参考示例,在什么情况下更好
- 为什么要拿参考的地址给我一个第二等级的指针
- 如何提升::序列化指针和参考
- 在范围外丢失指针参考
- 将std ::向量作为指针参考
- 从指针参考C 创建一个新对象
- 从基本指针/参考调用正确的免费功能
- 在操作员过载的情况下处理悬空指针/参考