简体   繁体   English

++运算符对char *做了什么

[英]What does an ++ operator do on char *

I got a source code from the web, but one line is ambiguous to me. 我从网上获得了一个源代码,但有一行对我来说很模糊。 I have a function: 我有一个功能:

double dict(const char *str1, const char *str2) {

and a line in this function as: 并且此函数中的一行为:

if (strlen(str1) != 0 && strlen(str2) != 0)
    while (prefix_length < 3 && equal(*str1++, *str2++)) prefix_length++;

what does the operator ++ do in *str1++ and *str2++? 运算符++在* str1 ++和* str2 ++中做了什么?

The ++ operator in *str++ increments the pointer (not the thing pointed at). *str++++运算符递增指针(不是指向的东西)。

(*str)++;   /* Increment the character pointed at by str */
 *str++;    /* Increment the pointer in str */
*(str++);   /* Increment the pointer in str - the same, but verbose */

There are two very different operations shown (one of them shown using two different but equivalent notations), though they both return the character that str pointed at before the increment occurs. 显示了两个非常不同的操作(其中一个显示使用两个不同但等效的符号),尽管它们都返回在增量发生之前str指向的字符。 This is a consequence of the precedence rules in the standard — postfix operators like ++ have higher precedence than unary (prefix) operators like * unless parentheses are used to alter this. 这是标准中的优先规则的结果 - 像++这样的后缀运算符具有比*类的一元(前缀)运算符更高的优先级,除非使用括号来改变它。

When you read or write to *str1++ , the normal rules for postfix increment are applied. 当您读取或写入*str1++ ,将应用后缀增量的常规规则。 That is: 那是:

  1. The pointer is incremented to the next address 指针递增到下一个地址
  2. The previous pointer value is returned 返回先前的指针值

At that stage you dereference the pointer value (which is the value prior to incrementing) and use the value it points to. 在那个阶段,你取消引用指针值(这是递增之前的值)并使用它指向的值。

*str1++ means first use the value pointed by str1 and then increment str1 *str1++表示首先使用*str1++value pointed by str1 ,然后递增str1

char arr[] = "meow";
char ch;

char *str = arr;

ch = *str++;    // ch = *(str++) both does same

Now, after executing above statement, 现在,执行上述声明后,

  1. ch will contain 'm' ch将包含'm'
  2. str will point to address of arr[1] str将指向arr[1]地址arr[1]

in C (and some derived languages) the char type is also a number type (a small one that can contains 256 different values), so you can do arithmetic operations on it, like addition ( +2 ), increment ( ++ ) and so on. C (和一些派生语言)中, char类型也是一个number类型(一个可以包含256个不同值的小类型),因此你可以对它进行算术运算,如加法( +2 ),增量( ++ )和等等。

in this case, the ++ operator doesn't increment the char but the pointer to this char. 在这种情况下, ++运算符不会增加char,而是指向此char的指针。

*str2++ returns the next address of the pointer to str2 *str2++返回指向str2的指针的下一个地址

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

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