2011-04-27 147 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