Chinaunix首页 | 论坛 | 博客
  • 博客访问: 509823
  • 博文数量: 61
  • 博客积分: 10352
  • 博客等级: 上将
  • 技术积分: 2840
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-10 14:43
文章分类

全部博文(61)

文章存档

2009年(2)

2008年(59)

我的朋友

分类: C/C++

2009-04-25 02:01:50

  下面的这个程序是一个变长数组应用的示例,  
  利用了C语言编译器不检查数组下标,  
  开始定义了一个空数组char   s[],  
  程序中可以动态增加s的长度。

 

#include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
   
  struct _t {
          size_t size;
          char s[];
  };
   
  int main()
  {
          struct _t *t;
   
          t = (struct _t *)malloc(sizeof (struct _t) + 10 * sizeof (char));
          if (!t) {
                  fputs("Out of memory.", stderr);
                  return 1;
          }
          t->size = 10;
   
          strncpy(t->s, "1234567891234567891234", t->size - 1);
          t->s[t->size-1] = '\0';
   
          puts(t->s);
   
          free(t);
   
          return 0;
  }


差不多懂了

阅读(499) | 评论(3) | 转发(0) |
0

上一篇:注意 c++ vector中的erase()

下一篇:Google hack

给主人留下些什么吧!~~

chinaunix网友2009-05-12 22:29:27

在char s[]; 的括号里加上任意非负整数都是可以的,应该不能为0(为0的意义是什么呢,c不允许吧)

chinaunix网友2009-05-11 16:48:52

唔,修改的话,malloc(sizeof (struct _t)要改为malloc(sizeof (size_t)

chinaunix网友2009-05-11 16:46:57

忐忑不安地留言: 这个好像毫无意义,在char s[]; 的括号里加上任意非负整数都是可以的,比如0,不影响后面程序。 是不是?