简体   繁体   English

不明白这个for循环是如何工作的

[英]Don't understand how this for loop works

Can someone explain how this loop works? 有人可以解释这个循环如何工作? The entire function serves to figure out where in hash to place certain strings and the code is as follows: 整个函数用于确定散列中放置某些字符串的位置,代码如下:

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

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

    return sum % size;
}

It seems to iterate over the string character by character until it hits null, however why does simple *str works as a condition? 它似乎逐字符遍历字符串,直到它达到null为止,但为什么简单的* str作为条件? 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? 为什么str ++移动到下一个字符,不应该是这样的:*(str + i)其中i随每个循环递增并根据* str地址在内存中移动“i”位置?

In C, chars and integers implicitly convert to booleans as: 0 - false, non-zero - true; 在C中,字符和整数隐式转换为布尔值为:0 - false,非零 - true;

So for(; *str; str++) iterates until *str is zero. 因此for(; *str; str++)迭代直到*str为零。 (or nul) (或零)

str is a pointer to an array of chars. str是指向字符数组的指针。 str++ increments this pointer to point to the next element in the array and therefore the next character in the string. str++将此指针递增为指向数组中的下一个元素,从而指向字符串中的下一个字符。

So instead of indexing by index. 因此,而不是索引索引。 You are moving the pointer. 你正在移动指针。

The condition in a for loop is an expression that is tested for a zero value. for循环中的条件是测试零值的表达式。 The NUL character at the end of str is zero. str末尾的NUL字符为零。

The more explicit form of this condition is of course *str != '\\0' , but that's equivalent since != produces zero when *str is equal to '\\0' . 这种情况的更明确的形式当然是*str != '\\0' ,但这是等价的,因为!=*str等于'\\0'时产生零。

As for why str++ moves to the next character: that's how ++ is defined on pointers. 至于为什么str++转移到下一个字符:这就是指针上定义的++ When you increment a char* , you point it to the next char -sized cell in memory. 增加char* ,将其指向内存中的下一个char -sized单元格。 Your *(str + i) solution would also work, it just takes more typing (even though it can be abbreviated str[i] ). 你的*(str + i)解决方案也可以工作,它只需要更多的输入(即使它可以缩写为str[i] )。

This for loop makes use of pointer arithmetic . 这个for循环使用指针算法 With that you can increment/decrement the pointer or add/substract an offset to it to navigate to certain entries in the array, since array are continuous blocks of memory you can do that. 使用它可以递增/递减指针或向其添加/减去偏移量以导航到数组中的某些条目,因为数组是连续的内存块,您可以这样做。

str points to a string. str指向一个字符串。 Strings in C always end with a terminating \\0 . C字符串总是以终止\\0结尾。

*str dereferences the actual pointer to get the char value. *str 取消引用实际指针以获取char值。

The for loop's break condition is equivalent to: for循环的中断条件相当于:

*str != '\0'

and

str++

moves the pointer forward to next element. 将指针向前移动到下一个元素。

The hole for-loop is equivalent to: 孔for循环相当于:

int len = strlen(str);
int i;
for(i = 0; i < len; i++)
    sum += str[i];

You could also write is as while-loop: 你也可以写为while-loop:

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

It has to do with how C converts values to "True" and "False". 它与C如何将值转换为“True”和“False”有关。 In C, 0 is "False" and anything else is "True" 在C中,0是“假”而其他任何东西都是“真”

Since null (the character) happens to also be zero it evaluates to "False". 由于null(字符)恰好也为零,因此它的计算结果为“False”。 If the character set were defined differently and the null character had a value of "11" then the above loop wouldn't work! 如果字符集的定义不同,并且空字符的值为“11”,则上述循环将不起作用!

As for the 2nd half of the question, a pointer points to a "location" in memory. 至于问题的后半部分,指针指向内存中的“位置”。 Incrementing that pointer makes it point to the next "location" in memory. 递增该指针使其指向内存中的下一个“位置”。 The type of the pointer is relevant here too because the "Next" location depends on how big the thing being pointed to is 指针的类型在这里也是相关的,因为“下一个”位置取决于被指向的东西有多大

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?

In C/C++, string is a pointer variable that contains the address of your string literal.Initially Str points to the first character.*(str) returns the first character of string. 在C / C ++中,string是一个指针变量,它包含字符串文字的地址.Initially Str指向第一个字符。*(str)返回字符串的第一个字符。

Str++ points to second charactes.Thus *(str) returns the second character of the string. Str ++指向第二个字符。因此*(str)返回字符串的第二个字符。

why does simple *str works as a condition? 

Every c/c++ string contains null character.These Null Characters signify the end of a character string in C. ASCII code of NUL character is 0 . 每个c / c ++字符串都包含空字符。这些空字符表示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.
{
}

When the pointer points to a null character it is regarded as false. 当指针指向空字符时,它被视为假。 This happens in pointers. 这在指针中发生。 I don't know who defined it, but it happens. 我不知道是谁定义的,但它发生了。

It may be just becuase C treats 0 as false and every other things as true. 这可能只是因为C将0视为虚假而其他所有事情都是真实的。

For example in the following code. 例如,在以下代码中。

if(0) {
           puts("true");
} else {
           puts("false"); 
}

false will be the output false将是输出

The unary * operator is a dereference operator -- *str means "the value pointed to by str ." 一元*运算符是一个引用操作- *str的意思是“价值的指向str 。” str is a pointer, so incrementing it with str++ (or ++str ) changes the pointer to point to the next character. str是一个指针,因此用str++ (或++str )递增它会将指针更改为指向下一个字符。 So it is the correct way to increment in the for loop. 所以这是在for循环中递增的正确方法。

Any integral value can be treated as a Boolean. 任何整数值都可以视为布尔值。 *str as the condition of the for loop takes the value pointed to by str and determine if it is non-zero. *str作为for循环的条件获取str指向的值并确定它是否为非零。 If so, the loop continues Once it hits a null character, it terminates. 如果是这样,循环继续一旦它命中空字符,它就会终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM