POD
POD

Reputation: 519

What does the "++" operator do on a "char *"?

In the following function:

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

There is the following:

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++?

Upvotes: 5

Views: 10996

Answers (4)

VoidPointer
VoidPointer

Reputation: 3107

*str1++ means first use the value pointed by str1 and then increment str1.

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

char *str = arr;

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

After executing the statement above:

  1. ch will contain 'm';
  2. str will point to the address of arr[1].

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754450

The ++ operator in *str++ increments the pointer (not the thing pointed at).

(*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. 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.

Upvotes: 7

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14106

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.

in this case, the ++ operator doesn't increment the char but the pointer to this char.

*str2++ returns the next address of the pointer to str2

Upvotes: 0

paddy
paddy

Reputation: 63481

When you read or write to *str1++, the normal rules for postfix increment are applied. 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.

Upvotes: 2

Related Questions