C 结构数组-删除/添加元素和打印

C 结构数组-删除/添加元素和打印,c,arrays,struct,printf,C,Arrays,Struct,Printf,对于下面的代码 struct orderSlip { char source[64]; char destination[64]; char item[64]; int position; }; //global struct orderSlip data[100]; 除了以下方法外,是否还有其他方法打印每个元素的数据: printf("%s\n",data[0].source); printf("%s\n",data[0].destination)

对于下面的代码

struct orderSlip
{
    char source[64];
    char destination[64];
    char item[64];  
    int position;
};
//global
struct orderSlip data[100];
除了以下方法外,是否还有其他方法打印每个元素的数据:

printf("%s\n",data[0].source);
    printf("%s\n",data[0].destination);
    printf("%s\n",data[0].item);
    printf("%i\n\n", data[0].position);

    printf("%s\n",data[1].source);
    printf("%s\n",data[1].destination);
    printf("%s\n",data[1].item);
    printf("%i\n", data[1].position);

但是在C中呢?我猜想它与Maloc和免费< /p> < P>删除和添加,是否必须构造一个动态数组?如果是,最简单的语法是什么?像C++代码这样的东西< /P> 如果您知道您的项目数量永远不会超过x,或者至少检查以确保您没有超过您计划的最大数量,那么您就不能使用静态数组

添加只需要有一个变量来跟踪数组中有多少项:

void add_item(struct orderSlip *p,struct orderSlip a,int * num_items)
{
   if ( *num_items < MAX_ITEMS )
   {
      p[*num_items] = a;
      *num_items += 1;
   }
}

选择性地

void print(const struct orderslip s, FILE *fp);


一种方法是分配数组中的每个元素,只保留一个指针数组

struct orderSlip **data;

data = calloc(100, sizeof(struct orderSlip*)); // 100 pointers to struct
(calloc将确保内存为零:从一开始就被删除)

每次添加新结构时:

data[i] = calloc(1, sizeof(struct orderSlip));
当你不再需要的时候

free(data[i]);
您还可以使用realloc更改数据的大小


如果您不需要使用索引访问数组,那么可以考虑另一种类型的数据结构(如链表是真正动态的)。

这是<代码> Dele[] BBBY;
,但是是的,在C中这样做需要
malloc/free
。我相信您可以通过一些搜索了解如何在C中使用动态数组;0是要删除的元素的位置;我可以删除任何位于别处的元素(1,2,3,4等),但如果我试图删除3个数组结构中的第一个,最后2个与元素2相同(如果有帮助,我使用qsort(),位置是关键)编辑:我发现错误:p[item]=p[item+1];假设为p[i]=p[i+1];现在它正确地删除了第一个元素!thanks@user1615805很高兴你找到我的虫子。这就是我只使用几个项目进行测试的结果…@user1615805看起来delete_item()中至少有两个bug。for循环太高了一个。它应该停在(size-2),而不是(size-1)。实际上,它已经停在了size-2,这就是“void print(const struct orderslip s);
void print(const struct orderslip s, FILE *fp);
void print(const struct orderslip *p, FILE *fp)
{
   fprintf(fp,"%s\n",p->source);
    ...
}
void print_all(const struct orderSlip *p, int num_items)



//global
struct orderSlip data[MAX_ITEMS];
int num_items = 0;



int main(void)
{
...
       print_all(data,num_items);                                       
       strcpy(a.source,"source 2");
       strcpy(a.destination,"destination 20");
       strcpy(a.item,"item xyz");
       a.position = 99;
       add_item(data,a,&num_items);
       print_all(data,num_items);
       delete_item(data,&num_items,0);
       print_all(data,num_items);
struct orderSlip **data;

data = calloc(100, sizeof(struct orderSlip*)); // 100 pointers to struct
data[i] = calloc(1, sizeof(struct orderSlip));
free(data[i]);