在C中使用指针进行循环 [英] For loop with pointer in C
问题描述
我不明白在for
循环中指针的作用. *p
在以下循环中做什么?
I don't understand what a pointer does in the for
loop. What does the *p
do in the following loop?
char str[128] = "Some Text";
char *p;
for (p = str; *p /*what does this mean?*/; p++)
{
// Code
}
我确实理解其余的内容,但是为什么*p
不像p > 3
或类似的东西?
为什么一个人呢?
为什么这样写?
I do understand the rest, but why isn't *p
like p > 3
or something like that?
Why is it alone?
Why is it written that way?
推荐答案
在布尔上下文中,例如for
循环的条件,C中的每个表达式求值为true(非零)或false(零).
In a Boolean context such as the condition of a for
loop, each expression in C evaluates to true (non-zero) or false (zero).
您希望for
循环在到达字符串末尾时终止.
You want the for
loop to terminate, when it reaches the end of the string.
在C中,每个字符串都以字符'\0'
终止,该字符实际上是0
.因此,当for
循环到达字符串的末尾时,*p
评估为'\0'
,即0
,其评估为false,从而终止for
循环.
In C, each string is terminated with the character '\0'
, which is practically 0
. So, when the for
loop reaches the end of string, *p
evaluates to '\0'
, which is 0
, which evaluates to false, which terminates the for
loop.
这篇关于在C中使用指针进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!