Bbvarghe
Bbvarghe

Reputation: 265

Incrementing pointers correctly?

I was using a char* array to copy parts of a string into another char* array, and I was wondering if doing this

do {
    *pntr1++ = *pntr2++
} while (*pntr2 != '\0');

is the same thing as

do
{
    *indPtr = *wordPtr;
    indPtr++;
    wordPtr++;
} while (*wordPtr != '\0');

or will I end up skipping an index from using the first method?

Upvotes: 0

Views: 105

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490038

Yes, the two are equivalent. A post-increment means the value before the increment is used in that expression, and the increment happens sometime before the sequence point at the end of the expression (or, in C++ terminology, "is sequenced before" the next expression).

Therefore, in both cases, the assignment uses the values of the pointers before they're incremented, and the comparison to \0 uses the value of the pointer after it's been incremented.

If you expect this to copy a string, that does lead to a problem: at least in the code you've shown, the \0 that terminates the (presumed) string won't get copied (though you could add code afterwards to terminate the destination string).

Upvotes: 3

Levans
Levans

Reputation: 14992

The operator ++ when used like a++ first returns the value of a and then increments it.

So, the codes

*a++ = *b++

and

*a = *b;
a++;
b++;

are equivalents.

Upvotes: 2

Related Questions