【问题标题】:memcpy confusion内存混乱
【发布时间】:2011-04-27 11:08:02
【问题描述】:

我试图将一个小数组复制到一个更大的数组中,但我不知道如何让它工作(程序在 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));          
    }

【问题讨论】:

  • 将 3000 替换为 300 或 30 会发生什么?
  • 你的问题是堆栈不够大。在堆上分配abyRaster。忠告:当您在 Stack Overflow 上发布问题时,请提供错误消息。说“程序总是崩溃”不是很有帮助。包含错误消息会对您的问题的质量产生很大影响。

标签: c memcpy


【解决方案1】:

代码看起来没问题,除了

unsigned char raster[3000*3000];

在堆栈上声明一个巨大的数组,您可能会用完此操作的堆栈空间(典型的堆栈大小只有几兆字节)。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      门廊

      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. 
      

      我个人发现“元素地址”语法(如下)比等效的数组基础加索引语法更不言自明......尤其是一旦你进入结构的偏移量。

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

      顺便说一句:我同意以前的其他海报...大于“一行”(例如 4096 字节)的所有内容都应该在堆上分配...否则您很快就会用完堆栈空间。只是不要忘记释放所有你 malloc 的东西......堆不像堆栈那样自我清理,而且 ANSI C 没有垃圾收集器(跟随你并在你之后清理)。

      干杯。基思。

      【讨论】:

        【解决方案4】:
        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 
        

        【讨论】:

        • 在答案中解释您的代码。它可以帮助您获得声誉。
        猜你喜欢
        • 2012-07-31
        • 2011-12-27
        • 1970-01-01
        • 2017-04-30
        • 2019-05-15
        • 2013-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多