Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: nums[SIZE] - next_num_ptr is invalid ptr arithmetic- it produces: invalid operands of types `int' and `int*' to binary `operator-'

...

In this noncompliant code example pointer subtraction is used to determine how many free elements are left in the nums array.

Code Block
bgColor#ffcccc

int nums[SIZE];
char *strings[SIZE];
int *next_num_ptr = nums;
int free_bytes;

/* increment next_num_ptr as array fills */

free_bytes = strings - (char **)next_num_ptr;

...

In this compliant solution, the number of free elements is kept as a counter and adjusted on every array operation. It is also calculated in terms of free elements instead of bytes. This prevents further mathematical errors.

Code Block
bgColor#ccccff

int nums[SIZE];
char *strings[SIZE];
int *next_num_ptr = nums;
int free_bytes;

/* increment next_num_ptr as array fills */

free_bytes = (nums[ + SIZE] - next_num_ptr) * sizeof(int);

...

In this noncompliant code example two iterators are subtracted that don't refer to the same vector.

Code Block
bgColor#ffcccc

vector<int> nums1(10, 0);
vector<int> nums2(10, 0);
vector<int>::iterator i1 = nums1.begin();
vector<int>::iterator i2 = nums2.begin();

int distance = i2 - i1;

...

In this compliant solution, both iterators point to the same vector, and the distance variable receives the expected value of 10.

Code Block
bgColor#ccccff

vector<int> nums1(10, 0);
vector<int> nums2(10, 0);
vector<int>::iterator i1 = nums1.begin();
vector<int>::iterator i2 = nums1.end();

int distance = i2 - i1;

...