我需要在函数中创建一个数组,我不能在main中声明它的大小,我用C ++开始我的冒险我写道:
#include <iostream>
using namespace std;
int create(int * n);
void display(int * arr, int * n);
int main()
{
int * n = new int;
int * arr = create(n);
display(arr, n);
delete n;
delete[] arr;
return 0;
}
int create(int * n) {
cout << "How many elements? ";
cin >> *n;
int * arr = new int[*n];
int element;
for(int i = 0; i < *n; i++) {
cout << endl << "Enter " << i << " array element: ";
cin >> element;
arr[i] = element;
}
return arr;
}
void display(int * arr, int * n) {
for(int i = 0; i < *n; i++) {
cout << endl << i << " element: " << arr[i];
}
}
编译器错误:error: invalid conversion from 'int*' to 'int' [-fpermissive]
请帮助我理解我在这里做错了什么。谢谢! :)
答案 0 :(得分:3)
您尝试从create()函数返回一个int,但是返回一个数组。一个简单的解决方法是将create()的签名更改为:
int* create(int* n);