【发布时间】:2021-11-18 19:28:46
【问题描述】:
我是 C 编程新手,我想知道它是如何读取数组中的字符串的。这是让我感到困惑的例子:
int main(void) {
char array[100] = {'a', 'b', 'c', '\0'};
// we add the '\0', so it doesn't read the entire array
array[98] = 'x';
// define that at index [98] there is character 'x'
char *p, *q;
// creates pointers
p = array;
// pointer p now points toward the address of the array,
// which is index [0]
printf("%s", p);
// Will print everything until a '\0' is reached,
// so print 'abc'
printf("%s", (p + 2));
// p is now pointing at the address of index[2],
// so print 'c'
q = &array[5];
// pass the address of index[5] to q
printf("%s", q);
// what is printed out?
}
我认为最后一行printf("%s", q); 会打印数组中的所有内容,直到到达\0,因为我们在printf 中指定了%s。所以,'x' 会被打印出来,但是当我运行程序时,什么都没有打印出来。这是为什么呢?
我明白了
abcc
您能否逐步解释一下当我阅读我的程序时会发生什么? (我是新手)
【问题讨论】:
-
你没有定义array[3]后面的内容,所以我相信标准说其余的必须用0初始化。所以array[5]是零,或者是零长度的字符串。跨度>
-
printf("%s", q);基本上是printf("");。您尝试打印一个零长度的字符串。 -
所以,我错误地认为 C 打印字符串的方式是打印每个单元格(内存空间)直到达到
\0? -
注意,
char array[100] = {'a','b','c','\0'};与char array[100] = "abc"完全相同。 -
由于数组是块范围变量(具有自动存储持续时间),因此数组中未初始化部分的值是不确定的。如果数组已在文件范围内声明或使用
static关键字(静态存储持续时间)声明,则可以保证将其初始化为零。