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

对于以下代码

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); 

等等

 for(int n = 0; n< 3; n++) { printf("%s\n",data[n].source); printf("%s\n",data[n].destination); printf("%s\n",data[n].item); printf("%i\n\n", data[n].position); } 

要删除和添加,我是否必须创建一个动态的结构数组? 如果是这样,最简单的语法是什么? 像这个c ++代码的东西

 int * bobby; bobby = new int [5]; delete bobby[5]; 

但在C? 我猜它与malloc和free有关

为了删除和添加,我是否必须创建一个动态的结构数组?如果是这样,那么最简单的语法是什么?像这个c ++代码一样

如果你知道你永远不会超过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; } } 

从静态数组中删除将需要一个for循环,它将上面的项目向下移动一个,并减少int跟踪项目的数量。

 void delete_item(struct orderSlip *p,int *num_items, int item) { if (*num_items > 0 && item < *num_items && item > -1) { int last_index = *num_items - 1; for (int i = item; i < last_index;i++) { p[i] = p[i + 1]; } *num_items -= 1; } } 

您可以通过将结构传递给执行工作的函数来简化结构的打印。

 void print(const struct orderSlip *p); 

要么

 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 

(calloc将确保内存为零:从头开始编辑)

每次添加新结构时:

 data[i] = calloc(1, sizeof(struct orderSlip)); 

当你不再需要时

 free(data[i]); 

您还可以使用realloc更改数据大小, 请参阅

如果您不需要使用索引访问数组,则可以考虑将其他类型的数据结构(如链接列表)视为真正动态的。