2013-06-26 223 views
0

可變長度數組(VLA)如何在內存中佔用空間?C++:可變長度數組

我觀察到VLA不佔用連續的內存空間,任何人都可以請確認相同的?

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操作,我的計劃是隻爲沃拉斯的幾個指標開始工作。 但用for代替memcpy Loop後,我的程序對所有VLA的索引都正常工作。

+2

在C++中沒有可變長度數組。如果我沒有記錯,gcc允許它們作爲擴展。 –

+1

只有C99有VLA! C++和其他版本的C可能會將它作爲編譯器擴展(這意味着VLA不是真正的語言的一部分,而是它的編譯器提供的功能)。 – Nawaz

+0

'memcpy(prevRowBuf,curRowBuf,width);'拷貝'width' _bytes_,而不是'width''int's。你需要'memcpy(prevRowBuf,curRowBuf,width * sizeof curRowBuf [324]);'('324'當然是任意的,你也可以使用'0',或'-3'或者'INT_MAX')。 –

回答

2

首先,C++的當前標準沒有VLA。但是,C++ 17可能。

我觀察到VLA不佔用連續內存空間,任何人都可以請確認一致嗎?

不,這是錯誤的。 VLA將佔用連續的空間。這個空間通常(總是?)來自堆棧而不是堆內存,就像靜態大小的C數組一樣。對於GCC extension for VLAs也是如此。