简体   繁体   English

为什么取消引用在 C/C++ 的这个 while 循环中只发生一次? [等候接听]

[英]Why does dereferencing occur only once in this while loop in C/C++? [on hold]

Why is *str in the following fragment dereferenced only once?为什么以下片段中的 *str 只取消引用一次? It takes the first character of the string 'a' and keeps incrementing this value until it reaches the end of the ASCII table, contrary to my expectation of dereferencing it on every condition evaluation and resulting in the infinite loop.它采用字符串“a”的第一个字符并不断增加该值,直到它到达 ASCII 表的末尾,这与我在每次条件评估时取消引用它并导致无限循环的期望相反。 This behavior does change even if the dereference is moved from the condition to the body of the loop.即使取消引用从条件移动到循环体,此行为也会发生变化。 GCC version 7.4.0 was used to test the code. GCC 版本 7.4.0 用于测试代码。

int getLen(char *str){
    int count=0;
    while((*str)++) {
        count++;
    }
    return count;
}

int main(){
    char s[]="abc";
    printf("length is %d\n",getLen(s));
}

Output: 159 Output:159

It is dereferenced 159 times, not just once.它被取消引用 159 次,而不仅仅是一次。

The ASCII value of a is 97 . a的 ASCII 值为97 If you increment that 159 times, you get 0 .如果你增加159次,你会得到0

(*str)++ doesn't increment str , it increments the first character in str . (*str)++不增加str ,它增加str中的第一个字符。

It doesn't increase it "until it reaches the end of the ASCII table", it increases until it becomes 0 .它不会增加它“直到它到达 ASCII 表的末尾”,它会增加直到它变成0 If your char type is signed, that means that it increments it to the maximum of that type, then from the minimum (a negative value) up to 0 .如果您的char类型是有符号的,这意味着它将它增加到该类型的最大值,然后从最小值(负值)增加到0

Typically, char is signed and 8-bits.通常, char是有符号的 8 位。 In that case, it will increase to 127 , the next value will be -128 and after that it will keep increasing until it becomes 0 .在这种情况下,它将增加到127 ,下一个值将是-128 ,之后它将继续增加直到变为0

If you want to use parentheses for clarity, use如果您想使用括号清楚起见,请使用

while (*(str++)) 
{
    count++;
}

That is the same as那是一样的

while (*str++)
{
    count++;
}

The term (*str)++ is the source of your problem.术语(*str)++是问题的根源。 You have added () around *str , which makes sure that *str is evaluated first and that value is incremented.您在*str周围添加了() ,这确保首先评估*str并且该值增加。 It never increments str .它永远不会增加str Use *str++ instead.请改用*str++

while(*str++) {
    count++;
}

The expression (*str)++ says, dereference str first, then increment the dereferenced value.表达式(*str)++表示,首先取消引用str ,然后增加取消引用的值。 It never increments str itself (the pointer).它永远不会增加str本身(指针)。 So, to answer your question, it's not that str is being dereferenced only once, it's dereferenced every time in the loop, but it never gets incremented hence the dereferenced memory is same every time.因此,要回答您的问题,并不是str仅被取消引用一次,而是在循环中每次都被取消引用,但它永远不会增加,因此取消引用的 memory 每次都是相同的。

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

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