删除/添加元素和印刷 - 结构的数组 [英] Array of structs - deleting/adding elements and printing
问题描述
对于低于code
struct orderSlip
{
char source[64];
char destination[64];
char item[64];
int position;
};
//global
struct orderSlip data[100];
是否有比下面这些方法的其他各元素打印出来的数据的另一种方法:
Is there another way of printing out the data for each element other than these methods below:
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 ++ code
For deleting and adding, do I have to make a dynamic array of structs? If so, what would be the simplest syntax to do that? Something like this c++ code
int * bobby;
bobby = new int [5];
delete bobby[5];
但在C?我猜它做malloc和free
but in C? I'm guessing it has do with malloc and free
推荐答案
的删除和添加,我必须作出结构的动态数组?如果是这样,这将是最简单的语法来做到这一点?事情是这样的C ++ code 的
如果你不知道,你永远不会比项目X数量更多或至少检查,以确保你没有超过你的计划是最大的。然后你可以使用你的静态数组。
Not if you know that you will never have more than x amount of items or at least check to make sure you aren't exceeding what you planned was the max. Then you can use your static array.
添加只需要你有一个跟踪有多少项目是数组中的变量:
Adding only requires you to have a variable that keeps track of how many items are in the array:
void add_item(struct orderSlip *p,struct orderSlip a,int * num_items)
{
if ( *num_items < MAX_ITEMS )
{
p[*num_items] = a;
*num_items += 1;
}
}
这一个静态数组删除将需要一个用于循环,将移动项目它上面向下和递减的项目数的整型保持轨道
Deleting from a static array would require a for loop that would move the items above it down one and decrementing the int keeping track of the number of items.
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;
}
}
您可以简化通过将其传递到执行工作的函数打印结构。
You could simplify printing the struct by passing it to a function that does the work.
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);
这篇关于删除/添加元素和印刷 - 结构的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!