memcpy 混淆
我正在尝试将一个小数组复制到一个更大的数组中,但我不知道如何让它工作(程序总是在 Visual studio 2008 x32 上崩溃)
memcpy 工作
memcpy( raster+(89997000), abyRaster, sizeof(abyRaster));
但不是
memcpy( raster+(line*3000), abyRaster, sizeof(abyRaster));
我只想让它在 for 循环中工作,但对指针算术以及 int 和 unsigned char 的大小感到困惑。
想法?
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));
}
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, sizeof(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));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
代码看起来没问题,只是
在堆栈上声明了一个巨大的数组,并且您可能会用完此操作的堆栈空间(典型的堆栈大小只有几兆字节)。
尝试使用
malloc
将raster
声明为动态数组。The code seems ok, except that
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, usingmalloc
.对于堆栈变量来说,
raster
数组相当大 (9 MB)。尝试从堆中分配它。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/ 说:
我个人认为“元素地址”语法(如下)比等效的数组基加索引语法更不言自明......尤其是一次你得到到结构数组的偏移量中。
顺便说一句:我同意之前其他海报的观点...所有大于“一行”(比如 4096 字节)的东西都应该分配在堆上...否则你很快就会耗尽堆栈空间。只是不要忘记释放您 malloc 的所有内容...堆不像堆栈那样具有自我清理功能,并且 ANSI C 没有垃圾收集器(跟随您并在您之后进行清理)。
干杯。基思.
portoalet,
http://www.cplusplus.com/reference/clibrary/cstring/memcpy/ says:
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.
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.