数组结构

  1. #define ERROR 0
  2. #define OK 1
  3. #define STUNUM 50

  4. #include <stdio.h>
  5. #include <string.h>

  6. struct STU
  7. {
  8.     char name[20];
  9.     char stuno[10];
  10.     int age;
  11.     int score;
  12. }stu[STUNUM];


  13. typedef struct LIST
  14. {
  15.     struct STU stu[STUNUM];
  16.     int length;
  17. }list, *plist;

  18. void printlist(list l)
  19. {
  20.     int i;
  21.     printf("name /tstuno /tage /tscore/n");
  22.     
  23.     for(i=0; i<l.length; i++)
  24.         printf("%8s /t%s /t%d /t%d/n"
  25.         l.stu[i].name, 
  26.         l.stu[i].stuno, 
  27.         l.stu[i].age, 
  28.         l.stu[i].score);    
  29.     printf("/n");
  30. }

  31. int listinsert(plist l, int i, struct STU e)
  32. {
  33.     struct STU *p, *q;
  34.     // cannot out of array
  35.     if (i<1 || i > l->length+1)
  36.         return ERROR;
  37.      
  38.      // array is full
  39.      if(l->length >= STUNUM)
  40.      {
  41.         printf("full/n");
  42.         return ERROR;
  43.      }
  44.      
  45.      // get the pos to insert 
  46.     q = &(l->stu[i-1]);
  47.     
  48.     // init first 
  49.     if (0 == l->length)
  50.     {
  51.         *q = e;
  52.         ++l->length;
  53.         return OK;
  54.     }
  55.         
  56.     // move from the last available to insert pos (with)
  57.     for(p = &l->stu[l->length-1]; p>=q; --p)
  58.         *(p+1) = *p;
  59.         
  60.     // assign it
  61.     *q = e;
  62.     
  63.     // increase length
  64.     ++l->length;
  65.     return OK;  
  66. }
  67. int main()
  68. {
  69.     struct STU e;
  70.     list l;
  71.     memset(&l, 0, sizeof(list));
  72.     l.length = 0;
  73.     int i;
  74.     strcpy(e.name, "gnuser");
  75.     strcpy(e.stuno, "10000");
  76.     for(i=0; i<10; i++)
  77.     {
  78.         e.age = 10;
  79.         e.score = i;
  80.         listinsert(&l, 1, e);
  81.     }
  82.     e.score = 11;
  83.     listinsert(&l, 5, e);
  84.     printf("List length now is%d./n/n", l.length);
  85.     printlist(l);
  86.     return 0;
  87. }
  88.         

关键点是插入时的移动,插一个要移动当前位置以及以后已经存在的元素,但按照索引查询很方便

  1.     printf("the 5th stu's record:/n");
  2.     printf("%d/n", l.stu[4].score); 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值