删除结构数组,更改结构地址
Deleting array of structures, changing structure adress
我动态创建了两个结构数组(player1和player1temp)。然后我想使用player1的数据进行一些计算,并将其保存到player1temp。然后我想复制数据从数组player1temp到player1。这是一个好的解决方案吗?
struct team
{
int value1;
int value2;
};
int main()
{
srand(time(NULL));
team *player1=new team[5];
for(int i=0; i<5; i++)
{
player1[i].value1=rand()%20;
player1[i].value2=rand()%20;
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"n";
}
team *player1temp=new team[5];
cout<<"nn";
for(int i=0; i<5; i++)
{
player1temp[i].value1=rand()%20;
player1temp[i].value2=rand()%20;
cout<<"Player1temp index: "<<i<<" "<<player1temp[i].value1<<" "<<player1temp[i].value2<<"n";
}
delete player1;
player1=player1temp;
cout<<"nn";
for(int i=0; i<5; i++)
{
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"n";
}
return 0;
}
两个错误:
如果用于数组,delete
应该是delete[]
。
在程序结束之前,也应该删除剩余的数组。
vector更简单:
struct team
{
int value1;
int value2;
};
int main()
{
srand(time(NULL));
std::vector<team> player1(5);
for(int i=0; i<5; i++)
{
player1[i].value1=rand()%20;
player1[i].value2=rand()%20;
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"n";
}
std::vector<team> player1temp = player1;
cout<<"nn";
for(int i=0; i<5; i++)
{
player1temp[i].value1=rand()%20;
player1temp[i].value2=rand()%20;
cout<<"Player1temp index: "<<i<<" "<<player1temp[i].value1<<" "<<player1temp[i].value2<<"n";
}
player1 = std::move(player1temp);
//don´t use player1temp anymore now
cout<<"nn";
for(int i=0; i<5; i++)
{
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"n";
}
return 0;
}
相关文章:
- 使用内存地址访问结构的属性值
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 指向结构的指针向量的元素具有相同的地址
- 如何获取结构体成员的地址
- 释放指向保留嵌套变量内存地址的结构的指针
- C++可以输出一个结构的内存地址吗
- 使用来自 C 的内存地址的 Julia 读取/写入结构数据
- 结构指针在"新"调用上给出已分配的地址?
- 使用指向结构变量成员的指针访问该结构的成员的地址
- 不太明白 & 运算符的地址在这个结构中做什么,以及它如何能够访问其他成员变量
- 函数中的结构指针的地址为0x1
- 无法找出此错误(将结构数组传递给函数):线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x1)
- C :变量的点地址至指针结构成员的地址
- 结构成员的地址作为编译时间常数之间的差异
- 将结构元素地址设置为C 中的null(单链接列表)
- C 在8086中获取类/结构地址
- C++ 套接字:结构地址的大小
- 删除结构数组,更改结构地址
- 在DLL中使用的结构地址