Why does my strCopy implementation work?

Here is the strCopy implementation

void strcopy2(char *dst, char const *src){ while ((*dst++ = *src++)) ; } 

Our professor asked us to reproduce this code without using pointers, so I came up with the following function:

 void strcopy(char dst[], char const src[]){ size_t i = 0; while (dst[i] = src[i++]) ; } 

This works well, but I realized that under the hood, the function should still use pointers, since we are not returning the value anywhere. In other words, although the latter function would use a pass by value, this is obviously not the case. So what happens under water, and is there any difference between the two methods?

+5
source share
3 answers

Not only under the hood & hellip; both dst and src , despite their appearance, are actually pointers! The syntax [] in the parameter lists is syntactic sugar (or syntactic pepper), but it lies to you; these are char* dst and char const* src for reals.

8.3.5 / 5 [dcl.fct] Functions:

After determining the type of each parameter, any parameter of type "array T" or type of function T is configured as a "pointer to T".

+14
source

Is there any difference between the two methods?

Yes, the second is incorrect:

 void strcopy(char dst[], char const src[]){ size_t i = 0; while (dst[i] = src[i++]) // (*) ; } 

A line labeled (*) is undefined behavior for most of C ++ history. There is no particular order of two readings of i relative to the increment. It is possible that this will be correctly ordered on your compiler on your platform. Perhaps the increment i will occur before it is read by the dst index, and your copy function will be disabled by one. In C ++ 17, the right side will be evaluated first, so the copy function is definitely disabled by one.

You want to make the increment your own expression:

 void strcopy(char dst[], char const src[]){ size_t i = 0; while (dst[i] = src[i]) { ++i; } } 
+3
source

This is a decay process.

for the compiler, the name of the array becomes a pointer to the first element.

Note that arrays and pointers do not match. this is a name, a character that is treated as a pointer to the first element of the array.

therefore, in your example, char dest[] treated by the compiler as &dest[0] , or, in other words, char* dest .

according to the language rules, if p is a pointer, then p[x] treated as *(p+x) , therefore the generated machine code in both examples is almost identical.

-1
source

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


All Articles