【发布时间】:2020-10-24 19:07:24
【问题描述】:
我需要打印存储在 int 数组中的值,当遇到 NULL 字符时停止 ('\0')。
所以我有这个代码:
const int display[10] = {1,4,8,2,0,9,2};
int main(){
int i = 0;
for (i = 0; i < 10; i++){
if (display[i] == '\0'){
break;
}
printf("%d\n", display[i]);
}
exit(0);
}
我希望打印display[10] 的所有值,或者在遇到'\0' 时中断,但我的代码在display[4] (0) 上中断,而不是继续到display[6]。
关于如何实现这一点的任何建议,避免在我的数组末尾打印空字符?
【问题讨论】:
-
整数数组不包含 NUL 字符。实际上,
\0只是 0,所以它在数组中的 0 处中断。 -
您可以从数组末尾搜索第一个非零值,但由于数组包含零,您无法知道尾随零是数据还是未使用。 OTOH,您可以定义
const int display[] = {1,4,8,2,0,9,2};并计算出尺寸。 -
0和'\0'是写同一件事的两种不同方式...与42和0x2A... 或for (;;) { /*...*/ }和while (1) { /*...*/ }相同