Chinaunix首页 | 论坛 | 博客
  • 博客访问: 220956
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-18 08:56:18

  1. /* tpop(1.5): growing array
  2.    created on Mar 17, 2011 */
  3. #include "stdio.h"

  4. typedef struct Nameval Nameval;

  5. struct Nameval {
  6.     char *name;
  7.     int value;
  8. };

  9. struct NVtab {
  10.     int nval;
  11.     int max;
  12.     Nameval *nameval;
  13. } nvtab;

  14. enum { NVINIT = 1, NVGROW = 2};

  15. /* main: growing array */
  16. int main(int argc, char *argv[])
  17. {
  18.       int i;
  19.      Nameval new;
  20.     new.name = "mark";
  21.     new.value = "23";
  22.     if ((i = addname(new)) != -1)
  23.      printf("Name is %s \n", nvtab.nameval[i].name);
  24.     i = delname("mark");
  25.     printf ("%d\n", i);
  26. }
  27. /* addname: add new name and value to nvtab */
  28. int addname(Nameval newname)
  29. {
  30.     Nameval *nvp;
  31.     if (nvtab.nameval == NULL) {/* first time */
  32.         nvtab.nameval = (Nameval *)malloc(NVINIT * sizeof(Nameval));
  33.         if (nvtab.nameval == NULL)
  34.          return -1;
  35.         nvtab.max = NVINIT;
  36.         nvtab.nval = 0;
  37.     } else if (nvtab.nval >= nvtab.max) { /* grow */
  38.         nvp = (Nameval *) realloc(nvtab.nameval, (NVGROW*nvtab.max) * sizeof(Nameval));
  39.         if (nvp == NULL)
  40.          return -1;
  41.         nvtab.max *= NVGROW;
  42.         nvtab.nameval = nvp;
  43.     }
  44.     nvtab.nameval[nvtab.nval] = newname;
  45.     return nvtab.nval++;

  46. }

  47. /* delname: remove first maching nameval from nvtab */
  48. int delname(char *name)
  49. {
  50.     int i;
  51.     for (i = 0; i < nvtab.nval; i++)
  52.      if (strcmp(nvtab.nameval[i].name, name) == 0) {
  53.          memmove(nvtab.nameval+i, nvtab.nameval+i+1, (nvtab.nval-(i+1)) * sizeof(Nameval));
  54.          nvtab.nval--;
  55.          return 1;
  56.      }
  57.     return 0;
  58. }
阅读(433) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~