Search code examples
c++arraysmemcpy

Correct size for memcpy for int arrays in C++


I'm new to C++ and would appreciate help with this problem. I've tried googling for examples, but can't seem to find quite what I'm looking for. I have a main function that allocates some space for an int array and a helper function (getRandomNumberArray) that populates that space with a random number array.

I'm printing the array as it is created in the helper function, and then after it's transferred to the memory allocated in the main function. And I lose a bunch of values inexplicably.

The code below outputs this:

95 70 24 40 26 7 84 45 62 13 41 11 21 55 23 50 17 8 76 20 94 25 90 29 95 26 9 44 47 8 61 27 42 10 15 26 53 64 55 90 79 28 72 46 50 87 86 36 87 33 33 29 4 65 56 65 12 30 14 59 25 42 69 99 47 2 42 25 80 90 32 51 17 14 74 83 94 34 92 88 51 85 78 71 9 38 54 17 34 19 47 89 73 43 38 99 48 8 84 81

95 70 24 40 26 7 84 45 62 13 41 11 21 55 23 50 17 8 76 20 94 25 90 29 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

As you can see, up to a point, the values are set, but then it's all zeros. Any idea what's going on here and how I can fix it?

Thanks!

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;


void getRandomNumberArray(int *result, int size){
    srand(time(0));

   int randomNos[100] = {0};

   for(int i = 0; i < 100; i++){
      randomNos[i] = rand() % 100 + 1;
      cout << randomNos[i] << ' ';
   }

   memcpy(result, randomNos,size);

}

int main() {
    int size = 100;
    int *randomNumbers = new int[size];
    getRandomNumberArray(randomNumbers,size);
    cout << "" << endl;
    for(int i = 0; i < 100; i++){
          cout << randomNumbers[i] << ' ';
       }

    free(randomNumbers);

   return 0;
}

Solution

    1. Why not just put if straight into the array in the first place?
    2. If you insist use memcpy(result, randomNos,size * sizeof(int));
    3. Using C++ you use delete[] not free
    4. Could be better off using vector - See http://www.cplusplus.com/reference/vector/vector/