Search code examples
cstringpointerschartypecast-operator

Getting length of string by typecasting it to int pointer in c


Going mad with string pointers, please help. Here is my question:

static int ByteOrder(
        char **charPtrPtr,
        long length,
        char *destPtr)
{
    char *endPtr = destPtr + length;

    while (destPtr < endPtr)
    {
        *destPtr++ = *((*charPtrPtr)++);
    }
    return 0;
}

int LenGet( char **charPtrPtr,
               long *lengthPtr)
{
    if (ByteOrder(charPtrPtr,
                sizeof(long),
                (char *)lengthPtr) != 0)
    {
        return 1;
    }

    printf("charPtrPtr: %s, lenPtr: %ld\n", *charPtrPtr, *lengthPtr);
    return 0;
}

int main()
{
    char *charPtr = "ffffff";
    long length = 0;

    LenGet(&charPtr, &length);
    printf("charPtr: %s, len: %ld\n", charPtr, length);
}
Output:
   charPtrPtr: ff, lenPtr: 1717986918
   charPtr: ff, len: 1717986918

In the above sections of code, what is the function ByteOrder does? I tried searching the answer for it, could not get it directly. I assume it copies all the stirngs from charPtrPtr to destPtr. And in the function LenGet, the lengthPtr returns the length of the string. Trying to understand this logic. Spent enough time in searching for it and now posting it here. If any links available for the same that helps me understanding this logic, please help me by posting it here or explaining it. Thanks, Denise.


Solution

  • In the above sections of code, what is the function ByteOrder does?

    The function does two things:

    1) It copies length characters from a source string to a destination string

    2) It advances the pointer to the source string by length

    It can be shown like this:

    enter image description here

    So the idea of the function is pretty simple. Copy N bytes and advance the pointer N positions - probably to indicate the next bytes to be processed.

    The function could be rewritten to something like:

    static int ByteOrder(
            char **charPtrPtr,
            long length,
            char *destPtr)
    {
        memcpy(destPtr, *charPtrPtr, length); // Copy characters
        *charPtrPtr += length;                // Advance source pointer
    
        return 0;  // Don't know why the function returns a fixed value
    }
    

    The rest of the code is horrible and probably violates strict aliasing.

    Anyway:

    The code copied the first 4 bytes of the source string into the integer variable length (and advanced the source string pointer by 4).

    Notice that length = 1717986918 = 0x66666666 and 0x66=102 which is the character 'f'.