我在MPI C中有一个用于图像处理的MPI程序(pgm文件),我按如下方式对2D数组使用动态分配。
float **masterbuf;
masterbuf = arralloc(sizeof(float), 2, M, N);
当我使用
时float masterbuf[M][N];
程序给出的图像看起来很好。
问题在于,当我使用动态分配时,图像左侧会丢失一些像素。所以这些缺失的像素会产生黑线。这就像图像已经向右移动了2个像素。我不对图像进行任何其他操作,只需读取并再次打印即可。
我用来写图像的功能是:
void pgmwrite(char *filename, void *vx, int nx, int ny)
{
FILE *fp;
int i, j, k, grey;
float xmin, xmax, tmp, fval;
float thresh = 255.0;
float *x = (float *) vx;
if (NULL == (fp = fopen(filename,"w")))
{
fprintf(stderr, "pgmwrite: cannot create <%s>\n", filename);
exit(-1);
}
printf("Writing %d x %d picture into file: %s\n", nx, ny, filename);
/*
* Find the max and min absolute values of the array
*/
xmin = fabs(x[0]);
xmax = fabs(x[0]);
for (i=0; i < nx*ny; i++)
{
if (fabs(x[i]) < xmin) xmin = fabs(x[i]);
if (fabs(x[i]) > xmax) xmax = fabs(x[i]);
}
if (xmin == xmax) xmin = xmax-1.0;
fprintf(fp, "P2\n");
fprintf(fp, "# Written by pgmwrite\n");
fprintf(fp, "%d %d\n", nx, ny);
fprintf(fp, "%d\n", (int) thresh);
k = 0;
for (j=ny-1; j >=0 ; j--)
{
for (i=0; i < nx; i++)
{
/*
* Access the value of x[i][j]
*/
tmp = x[j+ny*i];
/*
* Scale the value appropriately so it lies between 0 and thresh
*/
fval = thresh*((fabs(tmp)-xmin)/(xmax-xmin))+0.5;
grey = (int) fval;
fprintf(fp, "%3d ", grey);
if (0 == (k+1)%16) fprintf(fp, "\n");
k++;
}
}
if (0 != k%16) fprintf(fp, "\n");
fclose(fp);
}
答案 0 :(得分:2)
您对masterbuf的两个定义可能都会创建2D数组,但它们不会以相同的方式执行。函数arralloc()为数据和指针创建空间 - 而不仅仅是简单静态数组定义的数据。这意味着在pgmwrite()中,而x [i] [j]将返回相同的结果,无论使用何种方法,x [i]将意味着两个不同的东西,因为指针介入。
值得注意的是,如果您将原型中的void *vx
更改为float *vx
,编译器会为您提供线索。既然你立即无条件地将这个void *转换为float *,那么无论如何都要做到这一点要好得多。
(第二编辑:)此外,如果有兴趣,请查看此response。它显示了如何使用两个维度将索引编入单个malloc'd块,而不使用arralloc()。