Freigeben über


while(*a++=*b++);

For those who do not understand what "while(*a++=*b++);" does, I posted a sample in C# for you to know. I use C# beacuse I'm using a shared PC...

The key is that * means for a reference to a type when at type declaration, but when we use it in a statement * means that we want the content that is referenced by the pointer. In the sample below,  *a means tha we want the content of the character at the memory at some address that is holded by the pointer a; and when we use a++ we want to move forward the addres of the pointer to the next character. Another thing to know is that when use the assignmente operator = , it returns the value just assgined, so when you type char x =  *a = *b; x will have the value just copied from b adress to a adress. Last but not least, the while operator is looking for some value greater than 0 in order to continue the loop. If you remember you C/C++ classes all the strings finishes with a '\0' character that is equal to 0 as an integer value. That´s why the while breakes at the end of the string, and that´s why it´s can be used to copy strings.

 Obviously you wont use this code in real life, but could be interesting for those you are not experienced on pointers.

unsafe

{
    IntPtr ptrA = Marshal.StringToBSTR("hola"); // Convert Managed String to Unmanaged char array
    IntPtr ptrB = Marshal.StringToBSTR("HOLA"); // Convert Managed String to Unmanaged char array

    char* a = (char*)ptrA.ToPointer(); // Reference to the first character of string "hola"
    char* b = (char*)ptrB.ToPointer(); // Reference to the first character of string "HOLA"
    char* start = a; // Keep reference to the first character

    while ((*a++ = *b++) != 0); // Do the strcpy

    string str = Marshal.PtrToStringBSTR(new IntPtr(start)); // Converto Unmanaged char array to Managed String in order to print
    Console.WriteLine("STRCPY Result {0}", str);
    Console.WriteLine("Press any key to continue...");
    Console.ReadLine();
}

Comments