Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1605551
  • 博文数量: 585
  • 博客积分: 14610
  • 博客等级: 上将
  • 技术积分: 7402
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-15 10:52
文章存档

2013年(5)

2012年(214)

2011年(56)

2010年(66)

2009年(44)

2008年(200)

分类: C/C++

2011-08-23 10:27:04

    一直深信,数组长度必须是一个编译时可确定的常数,最近才发现自己真的是out了,自己真的是老了。

    C99标准已经支持变长数组,换言之,数组的长度可以在运行时确定,没有任何问题。但是有个问题,就是数组只能够声明,不能初始化,因为编译器并不知道数组的长度,无法初始化。
    请看下面的例子:
    第一个例子,表明数组长度可以直到运行时才确定。
    第二个例子表明,运行时才能确定长度的数组,不能初始化。
 
----------------------------正确使用变长数组的例子--------------------------------------------- 
#include

int test_array()
{
int a ;
        printf("please input the array's length \n");
scanf("%d",&a);
int b[a] ;

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

}

int main()
{
test_array();
return 0;
}

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

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

}

int main()
{
test_array();
return 0;
}


root@libin:~/program/C/array# gcc -o test test.c -pg
test.c: In function ‘test_array’:
test.c:8: error: variable-sized object may not be initialized
test.c:8: warning: excess elements in array initializer
test.c:8: warning: (near initialization for ‘b’
阅读(574) | 评论(0) | 转发(0) |
0

上一篇:treap的C实现

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

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