[英]Copying from a dynamic array to another dynamic array in c++ fpermissive
I have a array whose size is determined in runtime. 我有一个数组,其大小在运行时确定。
cout<<"Enter size of array: ";
cin>>size1;
int* scores=new int[size1];
Then I fill up this array scores. 然后我填写这个数组分数。 Now I want to increase its size. 现在,我想增加它的大小。 I create a new dynamic array. 我创建一个新的动态数组。
int* newScores=new int[newSize1];
such that `newSize1 > Size1
Now I copy content of old scores into newScores: 现在,我将旧乐谱的内容复制到newScores中:
for(int i=0; i<Size1;i++)
{newScores[i] = scores[i];
}
Now I have to ask remaining element of newScores to add to it. 现在,我必须要求将newScores的其余元素添加到其中。 I did: 我做了:
for(int j=size1;j<newSize1;j++)
{
newScores[j]=new int;
cout<<"Enter new score: ";
cin>>newScores[j];
}
While I compile it, I get the above error: 编译时,出现上述错误:
error: invalid conversion from 'int*' to 'int' [-fpermissive] newScores[size1]=new int;
newScores[j]=new int;
is an error, and not necessary. 是错误,不是必需的。 newscores[j]
is a lvlalue int
, while new int
returns int*
. newscores[j]
是lvlalue int
,而new int
返回int*
。 But you already have no need to allocate it - you did it in the int* newScores=new int[newSize1];
但是您已经不需要分配它-您在int* newScores=new int[newSize1];
expression. 表达。
You could avoid the thole hassle by using std::vector<int>
. 您可以通过使用std::vector<int>
避免麻烦。 It resizes itself automatically as you insert elements into it (with push_back
), and you don't have to worry about releasing the memory yourself. 当您向其中插入元素时,它会自动调整自身大小(使用push_back
),而您不必担心自己释放内存。
删除此行
newScores[j]=new int;
You do not need to assign new int to your dynamic array again. 您无需再次将新的int分配给动态数组。 Besides, you need to delete the memory by using delete[] when you use dynamic array 此外,使用动态数组时,需要使用delete []删除内存
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.