我对结构指针数组的增长有一个问题。
指向结构存储内存位置的指针。
但我不确定我想要存储多少。
我想要数组的动态增长。
我也可能需要删除其中一个元素。
代码如下:
#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);
另外,如果我想删除数组中的元素,该怎么做?
答案 0 :(得分:2)
在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;
答案 1 :(得分:0)
由于您将此标记为C和C ++,我将只回答其中一个:如果您想在C ++中使用此类行为,则不应自行实现。所有这些都已在标准模板库中完成。只需使用std :: list(如果你正在进行大量插入或从中间删除,并接受更长的项目查找时间)或std :: vector(如果你想要快速项目查找,但接受更长的时间来插入或删除列表中间的项目。)
查看您的代码:
std::list <dominate>