Quote:
Originally Posted by Konr This is beautiful. It's not relevant, but it's something everyone starting out in C should see. It's beautiful. It's by no means the safest string copy code ever, but it is beautiful. |
Hahaha. For those that don't understand what is going on, let me break it up:
while(....); simply refers to the fact that the while loop is empty. Normal while loops are done as while(....) { /* whatever */ }
*r++=*s++ could be better formatted this way:
*(r++) = *(s++)
Assuming r and s are arrays (including character arrays which are strings in C), where the beginning of an array is simply a memory address, that code simply says that whatever data is located the memory address pointed to by s should be copied into r at the memory address that r points to.
At the same time, it increments the memory address of r by sizeof(core_data_type_of_r) and the memory address of s by sizeof(core_data_type_of_s). An easy way to do that without worrying about the data type is to use sizeof(*r) and sizeof(*s) because *r and *s just refers to the first bit of data pointed to by r and s.
Lastly, the * operator with arrays (memory pointers) just "dereferences" the pointer, exposing the data. In simpler terms, *r is the data and r is the memory address, where *r might be 'C' and r might be 0x421C7F, for example.
Why would someone do that? Simply put, that is the fastest way to copy a string in C without the need for extra variables or functions.
Why wouldn't you just use r = s to copy the entire string? It is unsafe because you could overwrite data that was originally in s when you modify r and vice-versa. An example:
Before: r1 r2 r3 r4 0 s1 s2 s3 s4 s5 s6 s7 s8 0
r = s
After: <pointer to s> s1 s2 s3 s4 s5 s6 s7 s8 0
Now that r is merely a pointer to s, if you modify r or s, you also modify the other because they both point to the same memory address.