-
memcpy strange
Here is the code:
Code:
// set the array with values of 0
for (int index = 0; index < NumElements -1; index++) {
OriginalArray[index] = 0;
}
// forget about pure random at the moment
for (int index = 0; index < NumElements -1; index++) {
OriginalArray[index] = rand() % NumElements;
}
// stub for displaying numbers
for (index = 0; index < NumElements -1; index++) {
cout << OriginalArray[index] << '\t';
}
// copy the OriginalArray to the global RandomArray
memcpy(RandomArray, OriginalArray, NumElements-1);
cout << "\n\n\n\n";
// stub for displaying numbers
for (index = 0; index < NumElements -1; index++) {
cout << RandomArray[index] << '\t';
}
Here is some sample output:
Code:
6 4 3 9 6 4 1 0 6
// after 'copy'
6 4 3 0 0 0 0 0 0
What the? - rove
I cant figure out what is wrong, anyone see anything i cant?
-
> memcpy(RandomArray, OriginalArray, NumElements-1);
memcpy copies bytes, not ints
Try
memcpy(RandomArray, OriginalArray, sizeof RandomArray);
-
Thanks for the input, but that seems to make it worse, now only displaying 1 random number and following 0's. Is there a way to copy one element at a time and just loop it?
-
The third argument to memcpy is the number of bytes to copy so you want:
Code:
memcpy(RandomArray, OriginalArray, NumElements * sizeof(RandomArray[0]));
I'm suspicious of your use of NumElements - 1. Typically we don't want the - 1 because we are using the < operator and therefore for an array with 5 elements we get:
Code:
for (int index = 0; index < 5; index++) {
// index goes from 0 to 4
OriginalArray[index] = rand() % NumElements;
}
while with - 1 we get:
Code:
for (int index = 0; index < 5 -1; index++) {
// Index goes from 0 to 3
OriginalArray[index] = rand() % NumElements;
}
-
> Thanks for the input, but that seems to make it worse, now only displaying 1 random number and following 0's.
See, I thought from your variable name that it was an array in scope and not just a pointer to an array :mad:
-
Thanks that works now, yes your right the -1 was not ment to be there, i copied a stub from somewhere else in the code nice job :) saved me lots of headaches.
edit: salem your on the money 99% of the time ill forgive you this once! ;)