【发布时间】:2012-12-31 21:23:41
【问题描述】:
我目前正在学习 C,我对 char 数组和字符串之间的差异以及它们的工作方式感到困惑。
问题 1:
为什么源代码 1 和源代码 2 的结果会有差异?
源代码1:
#include <stdio.h>
#include <string.h>
int main(void)
{
char c[2]="Hi";
printf("%d\n", strlen(c)); //returns 3 (not 2!?)
return 0;
}
源代码2:
#include <stdio.h>
#include <string.h>
int main(void)
{
char c[3]="Hi";
printf("%d\n", strlen(c)); //returns 2 (not 3!?)
return 0;
}
问题 2:
字符串变量与 char 数组有何不同?如何用最小要求的索引号声明它们,允许存储 \0(请阅读下面的代码)?
char name[index] = "Mick"; //should index be 4 or 5?
char name[index] = {'M', 'i', 'c', 'k'}; //should index be 4 or 5?
#define name "Mick" //what is the size? Is there a \0?
问题 3:
终止的 NUL 是否只跟随字符串而不跟随字符数组?那么字符串“Hi”的实际值为[H][i][\0],而char数组“Hi”的实际值为[H][i]?
问题 4:
假设 c[2] 将存储 "Hi" 后跟 \0(不确定这是如何完成的,使用 gets(c) 可能吗?)。那么 \0 存储在哪里?它是存储在 c[2] 之后的“某处”变成 [H][i]\0 还是 c[2] 附加一个 \0 成为 c[3] 即 [H][i][\0 ]?
有时字符串/字符数组后面有一个 \0 并且当我通过 if (c1==c2) 比较两个变量时会导致麻烦,因为它很可能返回 FALSE (0),这很令人困惑。
感谢您提供详细的答案。但是保持你的回答简短有助于我的理解:) 提前谢谢!
【问题讨论】:
-
+1:很好的问题,很好的表述!