c – 不明白这个for循环是如何工作的
发布时间:2020-12-16 10:33:11 所属栏目:百科 来源:网络整理
导读:有人可以解释这个循环如何工作?整个函数用于确定散列中放置某些字符串的位置,代码如下: //determine string location in hashint hash(char* str){ int size = 100; int sum; for(; *str; str++) sum += *str; return sum % size;} 它似乎逐字符遍历字符串
有人可以解释这个循环如何工作?整个函数用于确定散列中放置某些字符串的位置,代码如下:
//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. { } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |