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

时间:2012-08-22 03:45:09

标签: 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);
    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和免费

有关

2 个答案:

答案 0 :(得分:5)

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

如果您知道自己的物品数量不会超过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);

答案 1 :(得分:2)

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

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 see

更改数据大小

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

相关问题