Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3835767
  • 博文数量: 146
  • 博客积分: 3918
  • 博客等级: 少校
  • 技术积分: 8584
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-17 13:52
个人简介

个人微薄: weibo.com/manuscola

文章分类

全部博文(146)

文章存档

2016年(3)

2015年(2)

2014年(5)

2013年(42)

2012年(31)

2011年(58)

2010年(5)

分类: C/C++

2011-08-06 01:46:59

    一直深信,数组长度必须是一个编译时可确定的常数,最近才发现自己真的是out了,自己真的是老了。
    C99标准已经支持变长数组,换言之,数组的长度可以在运行时确定,没有任何问题。但是有个问题,就是数组只能够声明,不能初始化,因为编译器并不知道数组的长度,无法初始化。
    请看下面的例子:
    第一个例子,表明数组长度可以直到运行时才确定。
    第二个例子表明,运行时才能确定长度的数组,不能初始化。
 
----------------------------正确使用变长数组的例子--------------------------------------------- 
  1. #include<stdio.h>

  2. int test_array()
  3. {
  4.     int a ;
  5.         printf("please input the array's length \n");
  6.     scanf("%d",&a);
  7.     int b[a] ;

  8.     printf("We can define a array with len we input\n");
  9.     b[a-1] = 3;
  10.     printf("the last element of array is %d\n",b[a-1]);
  11.     return 0;

  12. }

  13. int main()
  14. {
  15.     test_array();
  16.     return 0;
  17. }
  1. 下面是在我的Ubuntu 上用GCC编译及执行的情况。
  2. root@libin:~/program/C/array# gcc -o test test.c -pg
  3. root@libin:~/program/C/array# ./test
  4. please input the array's length
  5. 8
  6. We can define a array with len we input
  7. the last element of array is 3
  8. root@libin:~/program/C/array#
---------------------------------------------------------------------------------------------------------
  1. int test_array()
  2. {
  3.     int a ;
  4.     printf("please input the array's length \n");
  5.     scanf("%d",&a);
  6.     int b[a] = {0,};

  7.     printf("We can define a array with len we input\n");
  8.     b[a-1] = 3;
  9.     printf("the last element of array is %d\n",b[a-1]);
  10.     return 0;

  11. }

  12. int main()
  13. {
  14.     test_array();
  15.     return 0;
  16. }
  1. root@libin:~/program/C/array# gcc -o test test.c -pg
  2. test.c: In function ‘test_array’:
  3. test.c:8: error: variable-sized object may not be initialized
  4. test.c:8: warning: excess elements in array initializer
  5. test.c:8: warning: (near initialization for ‘b’

---------------------------------------------------------------------------------------------------------
阅读(7011) | 评论(0) | 转发(3) |
1

上一篇:及时终止的冒泡排序

下一篇:treap的C实现

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