[英]Handling dynamic growth of an array of pointers to structures
关于struct指针数组的增长我有一个问题。
指向结构存储内存位置的指针。
但我不确定我会想要存储多少。
我想要数组的动态增长。
我也可能需要删除其中一个元素。
代码如下:
#include <stdio.h>
#include <stdlib.h>
struct dominate * realloct(int* dim_1, struct dominate *dominateList)
{
int i;
struct dominate *dominateList_temp = (struct dominate *)malloc(sizeof(struct dominate *)*(*dim_1+10));
for(i = 0; i < *dim_1+10;i++)
{
if(i<*dim_1)
{
dominateList_temp[i] = dominateList[i];
//memcpy(b[i], a[i], (long)(sizeof(int)*(*dim_1)));
}
else
dominateList_temp[i] = (struct dominate *)malloc(sizeof(struct dominate *)*dim_1);
}
(*dim_1) = (*dim_1)+10;
return dominateList_temp;
}
struct dominate
{
double ID;
};
struct dominate *head;
int main()
{
int i;
struct dominate *dominateList;
struct dominate *dominateList_temp;
int dim_1 = 10;
struct dominate *z[100];
for(i = 0; i < 100; i++){
head = (struct dominate *) malloc(sizeof(struct dominate *));
head->ID = i;
z[i] = head;
}
dominateList = (struct dominate *)malloc(sizeof(struct dominate *)*dim_1);
for(i = 0; i < 100; i++){
if(i == dim_1 )
{
dominateList_temp = realloct(&dim_1, dominateList);
free(dominateList);
dominateList = dominateList_temp;
}
}
printf("%d \n\n", dim_1);
for(i = 0; i < 100; i++){
printf("%.2lf ", dominateList[i].ID);
printf("\n");
}
return 0;
}
我不知道如何修改这个问题
if(i<*dim_1){
dominateList_temp[i] = dominateList[i];
//memcpy(dominateList_temp[i], dominateList[i], (long)(sizeof(struct dominate *)*dim_1);
}
else
dominateList_temp[i] = (struct dominate *)malloc(sizeof(struct dominate *)*dim_1);
另外,如果我想删除数组的元素,该怎么做?
在C ++中,只需使用std::vector<dominate>
:
std::vector<dominate> d1;
d1.push_back(dominate()); // add a default constructed dominate object
std::vector<dominate> d2(100); // construct a vector with 100 default constructed dominate objects
dominate dom = ..... ;
d2[45] = dom;
既然你把它标记为C和C ++,我只会回答其中一个问题:如果你想在C ++中使用这种行为,你就不应该自己实现它。 所有这些都已在标准模板库中完成。 只需使用std :: list(如果你正在进行大量插入或从中间删除,并接受更长的项目查找时间)或std :: vector(如果你想要快速项目查找,但接受更长的时间来插入或删除列表中间的项目)。
看看你的代码:
std::list <dominate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.