C++:变长数组 [英] C++ : Variable Length Array

查看:61
本文介绍了C++:变长数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可变长度数组 (VLA) 如何占用内存空间?

How does Variable Length arrays (VLA) take space in memory?

我观察到 VLA 不占用连续的内存空间,谁能确认一下??

I have observed that VLAs do not take continuous memory space, can anyone please confirm the same??

void func(const IplImage *imgSrc, IplImage *imgDest)
{
  uchar *data = (uchar *)imgSrc->imageData;      

  // get the image data
  int height    = imgSrc->height;
  int width     = imgSrc->width;
  int step      = imgSrc->widthStep;
  int stepSobel = imgDest->widthStep;

  //Calculate Sobel of Image  
  uchar *dataSobel = (sobelStart + stepSobel);  

  //**Declaration of VLAs**
  int prevRowBuf[width],curRowBuf[width],nextRowBuf[width];

  for(int j=1;j<(width-1);j++)
  {    
    prevRowBuf[j] = data[j+1]-data[j-1];
    curRowBuf[j]  = data[step+j+1]-data[step+j-1];
  }

  // Some opencv processing
    for() // Some Conditions
    {

        //memcpy(prevRowBuf,curRowBuf,width);
        //memcpy(curRowBuf,nextRowBuf,width);

        //Replaced with
        for(int i=0 ; i< width; i++)
        {
          prevRowBuf[i]=curRowBuf[i];
          curRowBuf[i]=nextRowBuf[i];
        }
    } 
 }

通过两个 memcpy 操作,我的程序仅适用于 VLA 的几个起始索引.但是在将 memcpy 替换为 for 循环后,我的程序对 VLA 的所有索引都运行良好.

With the two memcpy operations, my program was working only for few starting indexes of VLAs. But after replacing the memcpy with for Loop my program is working fine for all the indexes of VLAs.

推荐答案

首先,C++ 没有 VLA.GCC 将它们实现为非标准扩展.

First off, C++ has no VLAs. GCC implements them as a nonstandard extension.

现在,在上述 GCC 扩展的上下文中回答您的问题:

Now, to answer your question in the context of said GCC extension:

我观察到 VLA 不占用连续的内存空间,有人能确认一下吗?

I have observed that VLAs do not take continuous memory space, can anyone please confirm the same?

不,那是错误的.VLA 将占用连续的空间.该空间通常(总是?)来自堆栈而不是堆内存,就像静态大小的 C 数组一样.

No, that is wrong. VLAs will take up continuous space. That space usually (always?) comes from the stack rather than the heap memory, just like statically sized C arrays.

这篇关于C++:变长数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆