【问题标题】:Segmentation Fault C (1d array to 2d array and back)分段错误 C(一维数组到二维数组并返回)
【发布时间】:2015-06-27 23:12:42
【问题描述】:

我得到一个包含图像像素颜色值的一维数组。该数组的大小为 cols*rows。我想更改特定区域的颜色。函数调用被赋予一维数组、它的大小、左、上、下、右以及所需的颜色。我试图做的是将一维数组的值复制到二维数组中,对二维数组执行操作,然后将新值复制回一维数组。我不断收到分段错误错误。代码如下:

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

到目前为止没有运气。

【问题讨论】:

  • uint8_t Array2[cols][rows]; --> uint8_t Array2[rows][cols]; ?

标签: c arrays 2d


【解决方案1】:

你应该这样做:

 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]!

【讨论】:

  • 感谢您的回复。我尝试了您的方法,但仍然出现分段错误错误。我不确定是什么原因造成的。
  • 我尝试切换它们,但问题仍然存在。
  • @user5056973 您是否尝试过使用调试器并查看发生了什么?
  • @user5056973 显然您会收到此错误,因为其中一个索引超出范围。
  • 我明白了,好吧,我不知道如何进一步帮助您,因为您应该编写一个独立的案例,而不是从某个地方粘贴一段代码。
猜你喜欢
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2016-05-07
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
相关资源
最近更新 更多