memcpy confusion
I am trying to copy a small array into a bigger array, and I could not figure out how to get it working (program always crashes on Visual studio 2008 x32)
memcpy work for
memcpy( raster+(89997000), abyRaster, sizeof(abyRaster));
but not
memcpy( raster+(line*3000), abyRaster, size开发者_JAVA技巧of(abyRaster));
I just want to get it working in the for loop, but got confused about the pointer arithmetic and the size of int and unsigned char.
Ideas ?
unsigned char raster[3000*3000];
unsigned char abyRaster[3000*1];
for( int line=0; line<3000;line++ ) {
int arrayPosition = line*3000;
memcpy( raster+(arrayPosition), abyRaster, sizeof(abyRaster));
}
The code seems ok, except that
unsigned char raster[3000*3000];
declares a huge array on the stack, and you may run out of stack space for this operation (typical stack sizes are just a few megabytes).
Try to declare raster
as a dynamic array, using malloc
.
That raster
array is quite large (9 MB) for a stack variable. Try allocating it from the heap.
portoalet,
http://www.cplusplus.com/reference/clibrary/cstring/memcpy/ says:
void * memcpy ( void * destination, const void * source, size_t num );
destination : Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
source : Pointer to the source of data to be copied, type-casted to a pointer of type void*.
num : Number of bytes to copy.
I personally find the "address-of-the-element" syntax (below) much more self-explanatory than the equivalent base-of-the-array-plus-the-index syntax... especially once you get into offsets-into-arrays-of-structs.
memcpy( &raster[arrayPosition], abyRaster, sizeof(abyRaster));
And BTW: I agree with the other previous posters... everything bigger than "one line" (say 4096 bytes) should be allocated on the heap... otherwise you VERY quickly run out of stack space. Just DON'T FORGET to free EVERYTHING you malloc... the heap isn't self-cleansing like the stack, and ANSI C doesn't have a garbage collector (to follow you around and clean-up after you).
Cheers. Keith.
The program can not be run directly because of not enough memory
If the system supports high enough the memory allocated by the program. then
the program copies bytes of a variable abyRaster to another variable on
every position (line*3000) of variable raster.
abyRaster[0] is copied to raster[0]
abyRaster[1] is copied to raster[3000]
abyRaster[2] is copied to raster[6000]
: :
: :
int line=0; line<3000;line++ used to identify only the index values of array
精彩评论