-1

I have made a dynamic copy of dynamic array, and the elements of the copy are not fully outputed. Also some numbers are printed with the wrong format.

My code:

// the function which outputs the elements of the array
void array_transform (double* num_array_1) {
for (int i = 0; i < sizeof(num_array_1); i++)
{
    cout << num_array_1[i] << endl;
}
// the code creating the copy
double* num_array_1 = new double[n];
memcpy(num_array_1, num_array, 4 * n);

The original array elements:

Array elements:
i       1       2       3       4       5       6       7       8       9       10
Number  42      68      35      1       70      25      79      59      63      65

The output of the copy:

42.00
68.00
35.00
1.00
70.00
-6277438562204192487878988888393020692503707483087375482269988814848.00
-6277438562204192487878988888393020692503707483087375482269988814848.00
-6277438562204192487878988888393020692503707483087375482269988814848.00

Please tell me why this is happening and how to fix this bug.

  • 2
    You probably missed the fact that `sizeof(num_array_1)` just gives you the size of that pointer variable itself (which is usually 8 bytes on modern architectures), and not the size of whatever you've been allocating before the function call. You need to keep track of that using a separate parameter, or simply use `std::array` or `std::vector`, which already do that correctly. – πάντα ῥεῖ Nov 16 '22 at 14:27
  • Also `4 * n` --> `sizeof(double) * n`. – molbdnilo Nov 16 '22 at 14:36

1 Answers1

0

memcpy is risky because you can get the size to copy wrong. This is the error you have made.

The correct code is

memcpy(num_array_1, num_array, sizeof(double) * n);

But a better way to copy is to use std::copy because with std::copy you don't have to specify the size of the element being copied. Here's how to copy your array with std::copy

#include <algorithm>

std::copy(num_array, num_array + n, num_array_1);
john
  • 85,011
  • 4
  • 57
  • 81