Adding to char*

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • seforo
    New Member
    • Nov 2006
    • 60

    Adding to char*

    Hi Guys,
    I have a segment of code here that I am not able to analyze
    [code=cpp]
    template <typename FieldType>
    int CheckHeaderFiel d(
    FieldType& field, const char* buffer, unsigned long bufferSize,
    bool continueParse
    )
    {
    const char* fieldptr = reinterpret_cas t<const char*>(&field);
    const char* endptr = buffer + bufferSize;
    AliHLTUInt32_t bufferRemaining = endptr > fieldptr ? endptr - fieldptr : 0;
    /*....And the rest of the code here*/
    }
    [/code]

    What is the meaning of adding a variable of unsigned long to a variable of char*
    I printed endptr but the output is just funny characters.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    When you add to a pointer, the compiler does a calculation to get the correct address as a result:
    [code=c]
    int arr[5];
    int* ptr= arr;
    ptr = ptr + 3;
    [/code]

    Assume the array is located at address 1000:

    1000 arr[0]
    1004 arr[1]
    1008 arr[2]
    1012 arr[3]
    1016 arr[4]

    So, ptr is initialized to the address of arr[0].

    When you add to a pointer, the address in the pointer is increased by the sizeof the type it points at. Here ptr is an int*. So, ptr + 3, will be
    ptr + 3 * sizeof(int). sizeof(int) is 4, so ptr is increased by 3*4, or 12.

    Location 1012 is &arr[3]. It is also &ptr[3]. It is also ptr + 3.

    To use the int at that location you can use arr[3], ptr[3], or *(ptr+3).

    Comment

    Working...