View Single Post
  #1 (permalink)  
Old 07-09-2007, 02:33 PM
rpgfan3233 rpgfan3233 is offline
PT Staff
Awards Showcase
Quality Tutorial Quality Tutorial Quality Tutorial Quality Tutorial 
Total Awards: 4
Join Date: Jul 2007
Posts: 118
iTrader: (0)
rpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura about
Icon8 Strings & Character Arrays

Quote:
Originally Posted by Konr View Post
This is beautiful. It's not relevant, but it's something everyone starting out in C should see.
Code:
while(*r++=*s++);
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.

__________________

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!

Last edited by rpgfan3233 : 07-09-2007 at 05:56 PM.
Reply With Quote