C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 不明白这个for循环是如何工作的大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_2@
有人可以解释这个循环如何工作?整个函数用于确定散列中放置某些字符串的位置,代码如下:

//determine String LOCATIOn in hash
int hash(char* str)
{
    int size = 100;
    int sum;

    for(; *str; str++)
        sum += *str;

    return sum % size;
}

它似乎逐字符遍历字符串,直到它达到null为止,但为什么简单的* str作为条件?为什么str移动到下一个字符,不应该是这样的:*(str i)其中i随每个循环递增并根据* str地址在内存中移动“i”位置?

解决方法

Why does str++ moves to the next character,shouldn't it be something like this
instead: *(str+i) where i increments with each loop and moves "i" places in 
memory based on *str address?

在C/C++中,String是一个指针变量,它包含字符串文字的地址.Initially Str指向第一个字符.*(str)返回字符串的第一个字符.

Str指向第二个charactes.Thus *(str)返回字符串的第二个字符.

why does simple *str works as a condition?

每个c / c字符串都包含空字符.这些Null字符表示C中字符串的结尾.NUL字符的ASCII码为0.

In C/C++,0 means falSE.Thus,NUL Character in Conditional statement 
means falSE Condition. 

for(;0;)/*0 in conditions means false,hence the loop terminates 
when pointer points to Null Character.
{
}
@H_404_2@

大佬总结

以上是大佬教程为你收集整理的c – 不明白这个for循环是如何工作的全部内容,希望文章能够帮你解决c – 不明白这个for循环是如何工作的所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。