首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >处理指向结构的指针数组的动态增长

处理指向结构的指针数组的动态增长
EN

Stack Overflow用户
提问于 2012-11-24 16:02:18
回答 2查看 106关注 0票数 0

我有一个关于结构指针数组增长的问题。

指向结构存储内存位置的指针数组。

但我不确定我想要存储多少。

我想要数组的动态增长。

我可能还需要删除其中一个元素。

代码如下:

代码语言:javascript
复制
#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;
}

我不知道如何修改这个问题。

代码语言:javascript
复制
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);

另外,如果我想删除数组中的一个元素,该怎么做?

EN

回答 2

Stack Overflow用户

发布于 2012-11-24 16:11:23

在C++中,只需使用std::vector<dominate>

代码语言:javascript
复制
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; 
票数 2
EN

Stack Overflow用户

发布于 2012-11-24 16:13:06

既然您将其标记为C和C++,我将只回答其中之一:如果您想在C++中实现这样的行为,您不应该自己实现它。所有这些都已经在标准模板库中完成了。只需使用std::list (如果您要从中间进行大量插入或删除,并接受较长的项目查找时间)或std::vector (如果您希望快速查找项目,但接受较长的插入或从列表中间删除项目的时间)。

看看你的代码:

  • 你使用C,所以你可能给它加上了错误的标记。
  • 你想要C
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13539449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档