c - for 循环在 C 中给出意想不到的结果

标签 c

我无法理解以下 for 循环。请帮我。谢谢你的时间。我无法理解 for 循环如何在第一次迭代中变为 true。如果 s[0] = "d",那么 "d"将如何被视为 "true"。

#include <stdio.h>

int main()
{
    char s[] = "d";
    int i;
    for(i = 0; s[i]; i++)
        printf("%c %c %c %c",s[ i ], *(s+i), *(i+s), i[s]);
    return 0;
}
output : dddd

最佳答案

根据C标准(6.5.2.1数组下标)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently,a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

所以 s[i] 等价于 *( s + i ) 从数学角度看等价于 *( i + s ) 在 C 中可以像 i[s] 一样重写,因为在任何情况下表达式都被视为 *( i + s )

因此所有这些结构

s[ i ] 
*(s+i) 
*(i+s) 
i[s]

在 C 中是等价的,表示数组 s 的第 i 元素。

至于你对我的回答的评论

Could you please explain how the for loop becomes true during the initial iteration?

然后数组 s 由字符串文字 "d" 初始化。

char s[ ] = "d";

字符串文字本身包含终止零字符'\0'。所以上面的声明实际上可以等价地重写为以下方式

char s[ ] = { 'd', '\0' };

由于数组的第一个元素不等于 0(它等于字符 'd'),因此条件 s[i] 等效当 i 等于 0 时,条件 s[i] != 0 为 true。

以及关于 for 语句的引用(6.8.5 迭代语句)

4 An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. The repetition occurs regardless of whether the loop body is entered from the iteration statement or by a jump.1

关于c - for 循环在 C 中给出意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892510/

相关文章:

c - 在C中从HTML <a></a>标签中解析URL的信息

c - 在 C 指针中查询

c - const char* 和 char* 转换(ADPCM 解码)

c++ - 重新分配的性能

c - 在 C 中读取和转换枚举类型

java - 递归反转链表的 C/C++ 到 Java 翻译

C - 如何检查不需要的字符是否在数组中?

c++ - "undefined behaviour"是否扩展到编译时?

C:打印多维数组中的整行

c - 如何在 C 中用 regexec 匹配一个数字