我使用这个函数的目的是使它成为这个数组的行翻转。基本上,第0行现在是最后一行,第1行现在是最后一行的下一行,依此类推。我有什么想法可以解决分段错误或者有更好的方法吗?谢谢,这是函数的代码:
ppmPic *flipVertical(ppmPic *pOriginal) {
ppmPic *newPic = malloc(sizeof(ppmPic));
newPic = pOriginal;
for(int a=0; a<newPic->rows; a++) {
for(int b=0; b<newPic->cols; b++) {
newPic->pixels[a][b].red = newPic->pixels[newPic->rows - a][b].red;
newPic->pixels[a][b].green = newPic->pixels[newPic->rows - a][b].green;
newPic->pixels[a][b].blue = newPic->pixels[newPic->rows - a][b].blue;
}
}
return newPic;
}
答案 0 :(得分:1)
您的代码的一个明显问题是副本行:
newPic->pixels[a][b].red = newPic->pixels[newPic->rows - a][b].red;
识别行的值范围是[0 .. rows-1]。您的第一个作业将引用pixels[rows]
,这是一个错误的1。您正在引用无效的数组索引。
你可能想要从源图像复制。所以你真的应该这么说:
newPic->pixels[a][b].red = pOriginal->pixels[pOriginal->rows - a][b].red;
我不是百分百肯定,但我相信你对ppmPic的定义引用了this site所指的相同内容。
在这种情况下,ppmPic的定义如下:
typedef struct ppm {
int rows;
int cols;
int colors;
Pixel **pixels;
} ppmPic;
typedef struct pixel {
int red;
int green;
int blue;
} Pixel;
如果我的假设是行数组中的ppmPic的pixels
成员(每行是列单元格的分配),则以下内容将翻转您的图像。我们将使用memcpy
来复制整行。
ppmPic* flipVertical(ppmPic *pOriginal)
{
ppmPic* newPic = malloc(sizeof(ppmPic));
int rows = pOriginal->rows;
int cols = pOriginal->cols;
// allocate an array of "rows"
Pixel** pixels = (Pixel**)malloc(rows * sizeof(Pixel*));
// now allocate each row, and copy from the original into it
for (int r = 0; r < rows; r++)
{
pixels[r] = (Pixel*)malloc(cols * sizeof(Pixel));
mempcy(pixels[r], pOriginal->pixels[rows-r-1], cols * sizeof(Pixel));
}
newPic.rows = rows;
newPic.cols = cols;
newPic.pixels = pixels;
newPic.colors = pOriginal->colors; // honestly, I'm not sure if colors is revelant here.. and if it is, that may mean that our allocation for each row needs to change
return newPic;
}