c - Indexes 2d array to 1d -
i want transform 2d array 1d. put important part of code.
int mask[3][3] = {{0, -1, 0}, {-1, 4, -1}, {0, -1, 0}}; (i = 1; < rows - 1; i++) { (j = 1; j < cols - 1;j++) { int s; s = mask[0][0] * image[i-1][j-1] + mask[0][1] * image[i-1][j] + mask[0][2] * image[i-1][j+1] + mask[1][0] * image[i][j-1] + mask[1][1] * image[i][j] + mask[1][2] * image[i][j+1] + mask[2][0] * image[i+1][j-1] + mask[2][1] * image[i+1][j] + mask[2][2] * image[i+1][j+1]; } }
my 1d array
for (k = rows + 1; k < (cols * rows) / 2; k++) { int s; s = 0 * image_in[k-rows-1] - 1 * image_in[k-rows] + 0 * image_in[k-rows+1] - 1 * image_in[k-1] + 4 * image_in[k] - 1 * image_in[k+1] + 0 * image_in[k+rows-1] - 1 * image_in[k+rows] + 0 * image_in[k+rows+1]; }
that should same don't know if correctly doing transformations. can tell me if ok?
first of all: why want away 2d array? think 2d array dimensions must constant? well, in case have news you: wrong. code should work perfectly:
int width = ..., height = ...; //create 2d array on heap dynamic sizes: int (*image_in)[width] = malloc(height * sizeof(*image_in)); //initialize array for(int = 0; < height; i++) { for(int j = 0; j < width; j++) { image_in[i][j] = ...; } }
you see, apart cryptic declaration of array pointer, indexing remains same automatic 2d array on stack.
within given loop, want address cells relative center cell. easiest done addressing relative cell:
for (i = 1; < rows - 1; i++) { (j = 1; j < cols - 1;j++) { int* center = &image_in[i][j]; int s = mask[0][0] * center[-width - 1] + mask[0][1] * center[-width] + mask[0][2] * center[-width + 1] + mask[1][0] * center[-1] + mask[1][1] * center[0] + mask[1][2] * center[1] + mask[2][0] * center[width - 1] + mask[2][1] * center[width] + mask[2][2] * center[width + 1]; } }
this works because 2d array has same memory layout 1d array (this guaranteed c standard).
the edge handling in 1d loop wrong: execute body of loop first , last cells of each line. this cannot fixed without introducing if()
statements loop slow things down.
this may ignored if consequences proven irrelevant (you still need exclude first , last lines plus cell). however, edge handling easier if stick 2d array.
Comments
Post a Comment