Pointer Arithmetic

When advancing a JCHAR pointer, it is important to advance the pointer by the correct number. In the example, the intent is to initialize each member of an array consisting of JCHAR strings to blank. Inside the "For" loop, the pointer is advanced to point to the next member of the array of JCHAR strings after assigning a value to one of the members of the array. This is achieved by adding the maximum length of the string to the pointer. Since pStringPtr has been defined as a pointer to a JCHAR, adding MAXSTRLENGTH to pStringPtr results in pStringPtr pointing to the next member of the array of strings.

#define MAXSTRLENGTH 10
JCHAR             *pStringPtr;
LPMATH_NUMERIC    pmnPointerToF3007;
for(i=(iDayOfTheWeek+iNumberOfDaysInMonth);i<CALENDARDAYS;i++)
{
  FormatMathNumeric(pStringPtr, &pmnPointerToF3007[i]);
  pStringPtr = pStringPtr + MAXSTRLENGTH;
}

These illustrations show the effect of adding MAXSTRLENGTH to pStringPtr. The top row in both tables contains memory locations; the bottom rows contain the contents of those memory locations.

The arrow indicates the memory location that pStringPtr points to before MAXSTRLENGTH is added to pStringPtr.

Example 1 of Unicode Pointer Arithmetic
Example 2 of Unicode Pointer Arithmetic

The arrow indicates the memory location that pStringPtr points to after MAXSTRLENGTH is added to pStringPtr. Adding 10 to pStringPtr makes it move 20 bytes, as it has been declared of type JCHAR.

Example 3 of Pointer Arithmetic

If pStringPtr is advanced by the value MAXSTRLENGTH * sizeof(JCHAR), then pStringPtr advances twice as much as intended and results in memory corruption.