gpt4 book ai didi

c - *s 等于 s[i] 吗?

转载 作者:行者123 更新时间:2023-11-30 20:48:22 24 4
gpt4 key购买 nike

K&R C 第 106 页,strcmp函数,它需要指针 *s*t作为参数,但在 for 中循环,它指定

s[i]==t[i]     

作为条件。

只是想确认一下,对于数组,如

*(s+i) and s[i] 

是同义的,因此函数语句可以使用 s[i]而不是*s

最佳答案

来自 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).

因此

a[i] 等价于 *( a + i ) 又等价于 i[a]

例如

int a[1] = { 10 };

printf( "a[0] == *( a + 0 ) is %s\n", a[0] == *( a + 0 ) ? "true" : "false" );
printf( "a[0] == 0[a] is %s\n", a[0] == 0[a] ? "true" : "false" );

关于c - *s 等于 s[i] 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41921145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com