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的索引都正常工作。
在C++中沒有可變長度數組。如果我沒有記錯,gcc允許它們作爲擴展。 –
只有C99有VLA! C++和其他版本的C可能會將它作爲編譯器擴展(這意味着VLA不是真正的語言的一部分,而是它的編譯器提供的功能)。 – Nawaz
'memcpy(prevRowBuf,curRowBuf,width);'拷貝'width' _bytes_,而不是'width''int's。你需要'memcpy(prevRowBuf,curRowBuf,width * sizeof curRowBuf [324]);'('324'當然是任意的,你也可以使用'0',或'-3'或者'INT_MAX')。 –