作者weii (迷惑失道)
看板SFFamily
标题[转录][心得]关於array initialization (阵列初始化) …
时间Fri Nov 28 11:50:18 2008
※ [本文转录自 C_and_CPP 看板]
作者: ikari512 ( //StrategyBass) 看板: C_and_CPP
标题: [心得]关於array initialization (阵列初始化)的笔记
时间: Fri Nov 28 00:49:37 2008
最近在版上问了一些关於array initialization的问题,还和高手同学讨论了一下
稍微整理笔记如下,来讨论看看有没有错...
以下都用gcc 4.1.2测试
(1.)array宣告了但没初始
int num[10]; //没初始
去读的话,都是垃圾值
(2a.)array宣告了,但只有部份初始(版本1)
int num[10];
num[0] = 999;
除了num[0]以外,也都是垃圾
(2b.)array宣告了,但只有部份初始(版本2,用大括弧)
int num[10] = {1,2,3}; //没初始完全
因为用大括弧,没初始的部份会自动补成0
这是因为...
(节录自tinlans大,英文是C99的一段)
[...If there are fewer initializers in a brace-enclosed list than there are
elements or members of an aggregate, or fewer characters in a string
literal used to initialize an array of known size than there are elements
in the array, the remainder of the aggregate shall be initialized
implicitly
the same as objects that have
static storage duration.
array 和 struct 这类东西在程式语言里都被归类为 aggregate (聚合资料)...]
粗略说就是...
如果aggregare型别(如array/struct)初始不完全,而且又是用大括弧方式初始,
就会像static变数一样,自动把没初始到的部份补0
所以,我们又可以知道
以下这种初始方式:
int num[10] = {0};
可以说对,也可以说错
因为照标准,这是部份初始化,又是array,所以其他也都会是0,看起来好像有初始效果
但这只是部份初始化的顺带效果,算你好运
如果compiler没照标准,这样就只有对第一个元素给值,其他就看天意,所以也算错
而且这样会造成误解,以为会全部都设成0
int num[10] = {255}; //之前版友的例子
这样其实只有第一个是255,其他都会是自动补的0,不是全部都是255
所以最好乖乖来,用memset,或是loop去初始
以上,有错请鞭 ._./~
--
//
IKARi
拥有追随自己内心与直觉的勇气,你的内心与直觉多少已经知道你真正想要成为什麽样的
人,任何其他事物都是次要的。
Steve Jobs
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.168.181.96
1F:推 williamyu:感谢整理:) 11/28 11:08
2F:推 chrisdar:int num[10] ={}; 这样写呢 11/28 11:20
3F:推 chrisdar:char num[10] = ""; 这样写呢 11/28 11:28
--
你凭什麽爱我...?
又凭什麽要走...!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.132.117.169