我正在实现一个稀疏的线性方程求解器,例如Lx = b。为此,我初始化了一个名为x_ref的参考x向量,并相应地生成一个RHS向量b。但是,两个指针似乎都为空。
VALUE_TYPE是宏,并设置为double
VALUE_TYPE *x_ref = (VALUE_TYPE *)malloc(sizeof(VALUE_TYPE) * n);
VALUE_TYPE *b = (VALUE_TYPE *)malloc(sizeof(VALUE_TYPE) * n);
for ( int i = 0; i < n; i++)
x_ref[i] = rand() % 10 + 1;
for (int i = 0; i < n; i++)
{
for (int j = cscColPtrTR[i]; j < cscColPtrTR[i+1]; j++)
{
int rowid = cscRowIdxTR[j]; //printf("rowid = %i\n", rowid);
b[rowid] += cscValTR[j] * x_ref[i];
}
}
将它们打印为;
for(int i = 0; i < n; i++)
{
printf("%d\t\t%d\n", x_ref[i], b[i]);
}
结果是:
4226166 1977719296
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
我不明白这是怎么回事。
答案 0 :(得分:1)
sizeof
中使用对象,而不要使用类型VALUE_TYPE *x_ref = (VALUE_TYPE *)malloc(sizeof(*x_ref) * n);
printf
格式。 %d
用于输出整数,而不是双精度数。#define VALUE_TYPE double
int main(void)
{
size_t n = 20;
VALUE_TYPE *x_ref = malloc(sizeof(*x_ref) * n);
VALUE_TYPE *b = malloc(sizeof(*b) * n);
for ( int i = 0; i < n; i++)
x_ref[i] = rand() % 10 + 1;
for ( int i = 0; i < n; i++)
printf("%d - %f\n", i, x_ref[i]);
}
答案 1 :(得分:-1)
首先,您不需要强制转换那些malloc,因为它返回一个void指针,因此强制转换是隐式的。我不确定为什么会得到这些零,但是有一些说明:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
// Use current time as seed for random generator
srand(time(0));
for(int i = 0; i<4; i++)
printf(" %d ", rand());
return 0;
}
由于引用未定义,我无法运行您的代码,但请考虑更正这些问题:)