简体   繁体   中英

Segmentation Fault C (1d array to 2d array and back)

I am given a 1d array that contains color values for an image's pixels. The array is of size cols*rows. I want to change the color of a specific region. The function call is given the 1d array, its size, left, top, bottom, right, and also the desired color. What I tried to do is copy the values of the 1d array into a 2d array, do the deed on the 2d array then copy back the new values to the 1d array. I keep getting a segmentation fault error. Here's the code:

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

    }   
}

I used this code to mirror the image horizontally and it worked:

    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;

    }
}

Then I adjusted it to try and make it work for the region_set function:

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

No luck so far.

You should do :

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

Other than that your code looks kind of messy, just take this approach. Also you seem to have written [cols][rows], instead of [rows][cols]!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM