C语⾔中⼆维字符数组的定义和初始化
继续将⼀些学习记录写下来,与⼤家分享。本篇⽇志关于⼆维字符数组的定义和初始化。我相信这篇⽂章属于菜鸟级的,⾼⼿请直接⽆视。
⼀般来说,我们可能会希望定义⼀个⼆维字符数组并且在定义的时候就⽤⼀些字符串来初始化它。⽐如说:
Code:
1. char testcase[30][MAX_LENGTH] = {"jo","vicent","tom","honey","gigi","lily","susan","peter","bob","ron",
2. "jason","henry","kiki","ken","auscar","vivian","yiyi","peace","iron","lotus"
3. "andy","arta","ophone","denial","pipe","wade","james","kobe","kent","angel"};
通常使⽤⼆维字符数组是为了在程序中存储⼀些字符串关键字。⽤这样的⽅式来初始化就最简单不过了。其中,MAX_LENGTH是所有字符串中最⼤的长度。当然不能忘记'/0'了。
⽽定义⼀个字符⼆维数组,C也提供了简洁的⽅式,如果我不想统计字符串的长度,我还可以这样定义:
Code:
1. char *testcase[30] = {"jo","vicent","tom","honey","gigi","lily","susan","peter","bob","ron",
2. "jason","henry","kiki","ken","auscar","vivian","yiyi","peace","iron","lotus"
3. "andy","arta","ophone","denial","pipe","wade","james","kobe","kent","angel"};
也就是说,可以不再数组定义的时候指定字符串的长度,但是注意字符串的个数是⼀定要指定的,像这样写 char **testcase = ... 是不⾏的,不过肯定不⾏了,因为int *pt=3 也不⾏,呵呵,这两个例⼦是⼀个道理啊。
我觉得肯定是⼈都喜欢第⼆种初始化⽅法了,⽽且它还有⼀个优点,起码对喜欢⽤指针的同志来说是⼀个⼤优点。就是可以将这样定义的指针赋给⼀个⼆维指针,⽐如
char **pointer = testcase;
想形式1的定义⽅法肯定不能这样赋值了。
c语言二维数组表示方法不过⾮常⾮常值得注意的是,上⾯定义的两个指针,⼀个⼀维,⼀个⼆维,他们必须在const关键字上⼀致,意思就是说如果定义testcase 前⾯加了const关键字,定义pointer时也必须加上,否则就会报错:
error C2440: 'initializing' : cannot convert from 'char *[30]' to 'const char **
在写这篇⽇志的过程中,我突然想到⼀个问题,就似乎利⽤上⾯的⽅法⼆初始化⼆维字符串数组之中,字符串是如何分布的呢?因为字符串的长度是不相等的,完全由编译器来计算,那么它是会按照最长的字符串来定制字符数组的长度,还是让每⼀个字符串数组都按照⾃⾝的⼤⼩来占据内存,靠'/0'来识别结尾呢?
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论