Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Similarly comparing pointers can tell you the relative positions of the pointers in term of each other. Subtracting or comparing pointers that do not refer to the same array can result in erroneous behavior.

It is acceptable to compare two member pointers within a single struct object, suitably cast, because any object can be treated as an array of unsigned char.

Non-Compliant Code Example

...

Code Block
bgColor#ffcccc
int nums[SIZE];
char *strings[SIZE];
int *next_num_ptr = nums;
int free_bytes;

/* perform operations onincrement next_num_ptr as array fills */

free_bytes = strings - (char *)next_num_ptr;

The first incorrect assumption is that nums and strings arrays will be next to each other are necessarily contingent in memory. The second is that free_bytes will be is the number of bytes available. The subtraction will return the number of elements between next_num_ptr and strings.

...

Code Block
bgColor#ccccff
int nums[SIZE];
char *strings[SIZE];
int *next_num_ptr = nums;
int free_elements = SIZEbytes;

/* perform operations on next_num_ptr as array fills decrement free_elements as it fills */

...