我在 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);
}
最佳答案
您的 masterbuf 的两个定义可能都创建 2D 数组,但它们的创建方式不同。函数arralloc()为数据和指针创建空间——而不仅仅是像简单静态数组定义那样的数据。这意味着在 pgmwrite() 中,虽然 x[i][j] 无论使用哪种方法都会返回相同的结果,但由于指针的参与,x[i] 将意味着两个不同的事情。
值得注意的是,如果您将原型(prototype)中的 void *vx
更改为 float *vx
,编译器会向您提供有关问题的线索。由于您立即无条件地将这个 void * 转换为 float *,因此无论如何这样做都是更好的做法。
(第二次编辑:)另外,如果有兴趣,请查看此 response 。它展示了如何使用二维索引到单个 malloc'd block 中,而不需要使用arralloc()。
关于c - C 中动态分配二维数组与简单二维数组 Mpi 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13578548/