在C中使用指针进行循环 [英] For loop with pointer in C

查看:149
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆