How is pointer assignment done in strcpy?

I look at the strcpy example where they increment the value of the pointer and assign it to 1 line, for example:

*ptrA++ = *ptrB++; 

I know that the value at which the pointer points to a char array is incremented and the content is copied.

does c something like

 *ptrA = *ptrB; ptrA++; ptrB++; 

in the background?

+2
source share
4 answers

Yes, remember that postfix ++ means the value before the increment. So * ptrA ++ increments ptrA, but returns ptrA dereferencing before incrementing.

+7
source

Good, yes and no.

Yes, because the second part of the code you provided does the exact same thing as the source code. So, in a sense, you correctly understood your source code.

No, because your second piece of code is not really equivalent to the original. Remember that it is incorrect to say that the postfix ++ operator first returns the original value and increments the pointer later. In C, temporal relationships (what happens before and what happens after) can only be determined by points in a sequence. Expression

 *ptrA++ = *ptrB++; 

it has no points of sequence inside, so it is absolutely impossible to say what happens before and what happens after. At the same time, your second option

 *ptrA = *ptrB; ptrA++; ptrB++; 

explicitly guarantees that the increment occurs after dereferencing, since there is a sequence point at the end of each operator. There are no such guarantees with respect to the first option. This is what I see as a problem with your interpretation.

In fact, it is entirely possible that the increment will happen first, and dereferencing will happen later. For example, the compiler might translate your original expression into something like

 tmp1 = ptrA++; tmp2 = ptrB++; *tmp1 = *tmp2; 

and in this case, the increment occurs first. Or the compiler can translate it into something like

 ptrA++; ptrB++; *(ptrA - 1) = *(ptrB - 1); 

and in this case, the increment also occurs first.

Remember once again that your interpretation of the original expression is good, but this is just one of the possible interpretations. Never assume that everything will happen in the specific order that you used in your interpretation.

PS About those points in the sequence: C FAQ , C ++ Frequently Asked Questions , Wikipedia

+7
source

Yes Yes. Since the code uses postfix operators:

Postfix operators are operators that are suffixes to an expression.

operand ++;

This causes the value of the returned operand. After the result is obtained, the value of the operand is increased by 1.

+2
source

Did you understand. (15 char)

+1
source

Source: https://habr.com/ru/post/896246/


All Articles