我想创建一个数组(称为Csend),然后创建一个稍微修改它的函数,例如向每个元素添加0.05。我遇到的问题是数组的格式化,我不确定如何正确地将它传递给函数。我已经在this guide之后以这种方式分配了内存,以便稍后我可以将它放在MPI_Send和MPI_Recv中。
这是我的尝试:
#include "stdio.h"
#include "stdlib.h"
#include "mpi.h"
#include "math.h"
int main(int argc, char **argv) {
int N = 32;
int dim = 3;
float a = 10.0; // size of 3D box
int size, rank, i, j, k, q;
float **C, **Csend, **Crecv;
float stepsize = 0.05;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
float **alloc_2d_float(int rows, int cols) {
float *data = (float *)malloc(N*dim*sizeof(float));
float **array= (float **)malloc(N*sizeof(float*));
for(i=0; i<N; i++) {
array[i] = &(data[dim*i]);
}
return array;
}
C = alloc_2d_float(N,dim);
Csend = alloc_2d_float(N,dim);
Crecv = alloc_2d_float(N,dim);
if(rank == 0) {
for (i = 0; i < N; i++) {
for (j = 0; j < dim; j++) {
Csend[i][j] = (float)rand()/(float)(RAND_MAX/a);
}}
}
// FUNCTION TO MODIFY MATRIX //
float randomsteps(float *matrix, int N, int dim) {
int i, j;
for(i = 0; i < N; i = i+2) {
for (j = 0; j < dim; j++) {
*((matrix+i*N) + j) = *((matrix+i*N) + j) + stepsize;
}
}
return matrix;
}
C = randomsteps(Csend, 32, 3);
for (i=0; i<N; i++){
for (j=0; j<dim; j++){
printf("%f, %f\n", Csend[i][j], C[i][j]);
}
}
MPI_Finalize();
return 0;
}
我遇到的问题是格式化,就像在这里一样,我收到错误消息,并以不提供错误消息的方式进行格式化,C只是空的。
以下是错误消息:
test.c: In function ‘randomsteps’:
test.c:46: error: incompatible types when returning type ‘float *’ but ‘float’ was expected
test.c: In function ‘main’:
test.c:49: warning: passing argument 1 of ‘randomsteps’ from incompatible pointer type
test.c:39: note: expected ‘float *’ but argument is of type ‘float **’
test.c:49: error: incompatible types when assigning to type ‘float **’ from type ‘float’
感谢您的帮助!
答案 0 :(得分:2)
您在矩阵的1维表示与指针逼近的二维指针之间混淆。
*((matrix+i*N) + j) = *((matrix+i*N) + j) + stepsize;
- &gt;这一行意味着matrix
只是线性集合,它使用索引操作像矩阵一样被访问。
float **C;
- &gt;这意味着您需要一个可以C[i][j]
访问的矩阵。
坚持任何一种陈述。此外,由于函数返回一个矩阵,如果你想要一个没有索引操作访问权限的2d矩阵,那么返回类型应该是float*
(如果2d矩阵被认为是线性的数组操作)float**
。 / p>
float* matrix = malloc(row * cols * sizeof(float)); // This is a linear version.
// matrix[i*cols + j] gives you the (i, j)th element.
float** matrix = malloc(rows * sizeof(float*));
for(int i = 0; i < rows; ++i)
matrix[i] = malloc(cols * sizeof(float));
// Now you can access matrix[i][j] as the (i, j)th element.
这是一种在两种格式之间进行互换的方法。
float* linearize(float** matrix, unsigned int rows, unsigned int cols)
{
float* linear = malloc(rows * cols * sizeof(float));
if(linear)
{
for(unsigned int i = 0; i < rows; ++i)
for(unsigned int j = 0; j < cols; ++j)
linear[i*cols + j] = matrix[i][j] ;
}
return linear ;
}
float** unlinearize(float* linear, unsigned int rows, unsigned int cols)
{
float** matrix = malloc(rows * sizeof(float*));
if(matrix)
{
for(unsigned int i = 0; i < rows; ++i)
{
matrix[i] = malloc(cols * sizeof(float));
if(matrix[i])
{
for(unsigned int j = 0; j < cols; ++j)
matrix[i][j] = linear[i*cols + j] ;
}
}
}
return matrix ;
}