Luc*_*vin 2 c++ arrays initialization dynamic
在我的代码中,我试图用initArray函数创建一个动态数组,在main中我想使用这个初始化数组.但是,每当我在main中调用初始化数组时,它都会给我一个错误.
这是我试过的:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我在main中执行initArray时,它可以工作.我究竟做错了什么?
我看到两个问题:
该函数接受一个指针.当你写的时候,A = ...你只是改变了按值传递给你的指针的副本.你可以使用void initArray(int* &A, int size),或让函数返回一个指针.
如果这是完整的代码,您可能需要该initArray函数的前向声明.
我究竟做错了什么?
不使用std::vector就是你做错了.
除此之外,假设这是学习或家庭作业或其他东西:
initArray(a,n);
Run Code Online (Sandbox Code Playgroud)
这条线的副本的int指针a.函数内部的副本被分配,main中的副本将保持为空.你需要使用pass-by-reference,通过C++引用或带有指针的C风格:
void initArray(int*& a, int size){
// everything the same
}
Run Code Online (Sandbox Code Playgroud)
这将修改main中的int指针而不进行任何其他更改.
void initArray(int** a, int size){
// need to dereference the pointer-to-pointer to access the int pointer from main
*a = new int[size];
for(/*...*/){
(*a)[i] = /*...*/;
}
}
Run Code Online (Sandbox Code Playgroud)
对于这个,您还需要更改呼叫方面:
initArray(&a, n); // pass pointer to a
Run Code Online (Sandbox Code Playgroud)
现在最后一件事:main甚至不知道initArray甚至存在.你需要把它放在上面main或至少向前声明它:
void initArray(int*& a, int size); // forward declaration
int main(){
// ...
}
void initArray(int*& a, int size){
// ...
}
Run Code Online (Sandbox Code Playgroud)
最后一件事,你需要delete[]在main中使用数组.