我有一個關於結構指針數組增長的問題。處理結構指針數組的動態增長
指向結構存儲內存位置的指針。
但是我不確定有多少我想存儲。
我想要數組的動態增長。
我也可能需要刪除其中一個元素。
代碼如下:
#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或C++無論是編碼,並適當地標記問題。 – NPE
你可能想要閱讀'man realloc'。 – alk