在我的code,我试图创建initArray功能的动态数组,并在主,我想利用这个初始化数组。但是,每当我叫主初始化数组,它给我一个错误。
In my code, I am trying to create a dynamic array with initArray function, and in main I would like to use this initialized array. However, whenever i called the initialized array in main, it is giving me an error.
下面是我尝试:
void main() { int *a = NULL; int n; cout<<"Enter size:"; cin>>n; initArray(a,n); for(int j=0;j<n;j++) { cout<<a[j]<<endl;//Crashes here } } void initArray(int *A, int size) { srand((unsigned)time(0)); A = new int[size]; for(int i=0;i<size;i++) { A[i] = rand()%10; } }当我在做的主要部分initArray,它的工作原理。我究竟做错了什么?
When i do initArray part in main, it works. What am i doing wrong?
推荐答案我看到两个问题:
函数接受一个指针。当你写 A = ... 你只改变了被按值传递给你的指针的副本。你可以使用无效initArray为(int *&安培; A,INT大小)。来代替,或者函数返回一个指针
the function accepts a pointer. When you write A = ... you're only changing the copy of the pointer that gets passed to you by value. You could use void initArray(int* &A, int size) instead, or have the function return a pointer.
如果这是完整的code,则可能需要在 initArray 函数的正向声明。
if that's the full code, you might need a forward declaration of the initArray function.
更多推荐
初始化和使用C中的动态数组++
发布评论