2011-04-27 148 views
0

我想小阵列复制到一个更大的阵列,我无法弄清楚如何得到它的工作(程序总是崩溃的Visual Studio 2008的32倍)的memcpy混乱

memcpy(raster+(89997000), abyRaster, sizeof(abyRaster)); 
的memcpy工作

但不

memcpy(raster+(line*3000), abyRaster, sizeof(abyRaster)); 

我只是想获得它的工作循环,但得到搞不清指针运算和int和无符号字符的大小。

想法?

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));   
    } 
+0

当你用300或30代替3000时它会发生什么? – 2011-04-27 11:11:47

+2

你的问题是堆栈不够大。在堆上分配'abyRaster'.A建议:当您在Stack Overflow上发布问题时,请提供错误消息。陈述“程序总是崩溃”并不是很有帮助。包括错误信息会对问题的质量产生重大影响。 – 2011-04-27 11:21:33

回答

4

的代码似乎确定,除了

unsigned char raster[3000*3000]; 

声明在堆栈上一个巨大的数组,你可能运行的堆栈空间进行此项操作(典型堆栈大小只是一个数兆字节) 。

尝试声明raster为动态数组,使用malloc

+0

从来没有想过堆栈大小是问题。谢谢。 – portoalet 2011-04-27 11:24:55

3

raster对于堆栈变量,数组非常大(9 MB)。尝试从堆中分配它。

0

portoalet,

http://www.cplusplus.com/reference/clibrary/cstring/memcpy/说:

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. 

我亲自找到“地址的最元素”语法(下)比同等更加不言自明基地的最-array-plus-the-index语法......特别是一旦你进入偏移量到结构数组。

memcpy(&raster[arrayPosition], abyRaster, sizeof(abyRaster)); 

而且BTW:我同意与其他先前的海报...一切不是“一条线”做大(比如4096个字节),应在堆上分配......否则你很快用完堆栈空间。只是不要忘记释放你所有的malloc ......堆不是像堆栈一样自我清理,而ANSI C没有垃圾收集器(跟随你并在你之后清理)。

干杯。基思。

0
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 
+0

在答案中解释你的代码。它可以帮助你获得名声。 – 2016-03-21 14:40:02