我有一个与我的C / C ++代码相关的问题。我尝试了一些研究,但没有针对我的问题的具体答案。我希望你能尽快回答我的问题。
以下是我在C语言中的完整代码:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define M 500
#define N 500
int
main ()
{
//set number of threads here
//omp_set_num_threads(8);
int i, j, k;
double sum;
double **A, **B, **C;
A = malloc (M * sizeof (double *));
B = malloc (M * sizeof (double *));
C = malloc (M * sizeof (double *));
for (i = 0; i < M; i++)
{
A[i] = malloc (N * sizeof (double));
B[i] = malloc (N * sizeof (double));
C[i] = malloc (N * sizeof (double));
}
double start, end;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
A[i][j] = j * 1;
B[i][j] = i * j + 2;
C[i][j] = j - i * 2;
}
}
start = omp_get_wtime ();
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
sum = 0;
for (k = 0; k < M; k++)
{
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
end = omp_get_wtime ();
printf ("Time of computation: %f\n", end - start);
cin.get ();
return 0;
}
由于一些错误,代码终止。 代码的结果在这里给出:
error C4700: uninitialized local variable 'A' used
error C4700: uninitialized local variable 'B' used
error C4700: uninitialized local variable 'C' used
请考虑我的问题:)
最诚挚的问候。
答案 0 :(得分:0)
malloc()返回一个void指针,你必须强制转换它:
A = (double**) malloc (M * sizeof (double *));
B = (double**) malloc (M * sizeof (double *));
C = (double**) malloc (M * sizeof (double *));
for (i = 0; i < M; i++)
{
A[i] = (double*) malloc (N * sizeof (double));
B[i] = (double*) malloc (N * sizeof (double));
C[i] = (double*) malloc (N * sizeof (double));
}
如果您使用的是c ++,最好使用“new”而不是malloc:
A = new double* [M];
B = new double* [M];
C = new double* [M];
for (i = 0; i < M; i++)
{
A[i] = new double[N];
B[i] = new double[N];
C[i] = new double[N];
}