分段故障C(1d阵列到2d阵列和后面)

时间:2015-06-27 23:12:42

标签: c arrays 2d

我获得了一个包含图像像素颜色值的1d数组。该数组的大小为cols *行。我想改变特定区域的颜色。函数调用给出了1d数组,它的大小,左,上,下,右,以及所需的颜色。我试图做的是将1d数组的值复制到2d数组中,在2d数组上执行deed,然后将新值复制回1d数组。我一直收到 细分错误 错误。这是代码:

void region_set( uint8_t array[], 
         unsigned int cols, 
         unsigned int rows,
         unsigned int left,
         unsigned int top,
         unsigned int right,
         unsigned int bottom,
         uint8_t color )
{

    if(!(left == right || top == bottom)){

        uint8_t Array2[cols][rows];

        int x, y;

        for(int i= 0; i < rows * cols; i++){            
            x = i / rows;
            y = i % cols;
            Array2[y][x] = array[i];
        }

        for(int y=left; y < right-1; y++){
             for(int x = top; x < bottom-1 ; x++){
                Array2[y][x] = color;
            }
        }

        for(int i= 0; i < rows * cols; i++){            
            x = i / rows;
            y = i % cols;
            array[i] = Array2[y][x];
        }

    }   
}

我使用此代码水平镜像图像并且工作正常:

    for(int x=0; x<cols; x++){
 for(int y =0; y< rows/2; y++){

    holdVal=array[x + y * rows];
    array[x + y * rows] = array[(rows-1-y)* rows + x];
    array[(rows-1-y) * rows + x] = holdVal;

    }
}

然后我调整它以尝试使其适用于region_set函数:

for(int y=left; y< right-1; y++){
         for(int x = top; x< bottom - 1; x++){
            array[x + y * cols] = color;
        }
    }

到目前为止没有运气。

1 个答案:

答案 0 :(得分:0)

你应该这样做:

 int k = 0;
 for(int i = 0; i < rows; ++i)
 {
     for(int j = 0; j < cols; ++j)
     {
          array[k++] = Array[i][j];
          // or
          Array[i][j] = array[k++];
     }
 }

除了你的代码看起来有点混乱,只需采取这种方法。 你似乎也写了[cols] [rows],而不是[rows] [cols]!