C++ basic array assignment is not working -
so have function
f(int d[],int a[],int len){ for(int k = 0; k < len; k++) d[k] = a[k];
and if output d
numbers wrong. function f
called d
initialised int* d = new int[100000];
in main
function , a
because output in function , looks ok. so... can't understand problem is... tried memcpy(d+k,a+k,sizeof(int));
, doesn't work.
your loop works perfectly. problem must somewhere else in code.
here example program copies data in 3 different ways: for
loop, memcpy
, , std::copy
:
#include <algorithm> #include <cstring> #include <iostream> #include <iterator> void copy1(int d[], int a[], int len) { for(int k = 0; k < len; k++) d[k] = a[k]; } void copy2(int d[], int a[], int len) { std::memcpy(d, a, len*sizeof(int)); } void copy3(int d[], int a[], int len) { std::copy(a, a+len, d); } int main () { int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int *d = new int[10]; std::ostream_iterator<int> out(std::cout, ","); // first, print initial values std::copy(d, d+10, out); std::cout << "\n"; // next copies , print values again copy1(d, a, 10); std::copy(d, d+10, out); std::cout << "\n"; copy2(d, a, 10); std::copy(d, d+10, out); std::cout << "\n"; copy3(d, a, 10); std::copy(d, d+10, out); std::cout << "\n"; }
the output is:
0,0,0,0,0,0,0,0,0,0, 1,2,3,4,5,6,7,8,9,10, 1,2,3,4,5,6,7,8,9,10, 1,2,3,4,5,6,7,8,9,10,
Comments
Post a Comment