2013-06-26 2 views
0

가변 길이 배열 (VLA)은 메모리에서 어떻게 공간을 차지합니까?C++ : 가변 길이 배열

나는 VLA가 연속적인 메모리 공간을 차지하지 않는다는 것을 관찰했다. 두 memcpy 작업으로

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]; 
     } 
    } 
} 

, 내 프로그램은 플 로브 디프의 몇 시작 인덱스 만 작업했다. 그러나 memcpyfor으로 바꾸면 내 프로그램이 VLA의 모든 색인에 대해 정상적으로 작동합니다.

+2

C++에는 가변 길이 배열이 없습니다. 올바르게 기억하면 gcc에서 확장자로 사용할 수 있습니다. –

+1

C99 만 VLA! C++ 및 다른 버전의 C에서는 컴파일러 확장 (VLA가 실제로 언어의 일부가 아니라 컴파일러에서 제공하는 기능)을 사용할 수 있습니다. – Nawaz

+0

'memcpy (prevRowBuf, curRowBuf, width);''width'_bytes_가 아니라'width'''''''를 복사합니다. 'memcpy (prevRowBuf, curRowBuf, width * sizeof curRowBuf [324]);'(324는 물론 임의적으로,'0' 또는'-3' 또는'INT_MAX'를 사용할 수도 있습니다)가 필요합니다. –

답변

2

먼저 C++의 현재 표준에는 VLA가 없습니다. 그러나 C++ 17은 그렇게 할 수 있습니다.

나는 VLA가 연속적인 메모리 공간을 차지하지 않는다는 것을 관찰했는데, 누구도이를 확인할 수 있습니까?

아니요, 틀 렸습니다. VLA는 연속적인 공간을 차지할 것입니다. 그 공간은 대개 정적 인 크기의 C 배열과 마찬가지로 힙 메모리가 아닌 스택에서옵니다.

GCC extension for VLAs에 대해서도 마찬가지입니다.