The problem statement, and the proposed “correct” solution, both, force readers to forego best memory safety practices in C and C++, and make assumptions that may result in undefined behavior but work accidentally. The proposed solution makes assumptions about Arr
that are not explicitly mentioned anywhere (e.g., use of delete[]
). Is Arr
a pointer to a stack-allocated array? Or a malloc’ed array? Or one allocated using operator new[]
? What does the caller expect? A malloc’ed or new[]
ed array?
Current problem statement:
Implement a function removeEven( int *& Arr, int size ) which takes an array arr and its size and removes all the even elements from a given array.
Proposed replacements:
Option (1):
Implement a function removeEven(std::vector& Arr) which takes an array arr and its size and removes all the even elements from a given array.
Option (2):
Implement a function removeEven( int *& Arr, int size ) which takes an array arr and its size and removes all the even elements from a given array; assume
Arr
was allocated withoperator new[]
.
PS: This is about the C++ course, but I cannot find it in “tags”, so selected the Java course.