初始化的指针全为0,而不是生成的值

时间:2020-06-11 10:36:43

标签: c pointers null malloc sparse-matrix

我正在实现一个稀疏的线性方程求解器,例如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

我不明白这是怎么回事。

2 个答案:

答案 0 :(得分:1)

  1. 请在sizeof中使用对象,而不要使用类型VALUE_TYPE *x_ref = (VALUE_TYPE *)malloc(sizeof(*x_ref) * n);
  2. 使用正确的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]);
}

https://godbolt.org/z/RKjZi8

答案 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; 
}
  • 使用memset初始化b向量,因为它们(据我所知)是累积值,因此它们应从0开始。到目前为止,您的向量可能只包含乱码。

由于引用未定义,我无法运行您的代码,但请考虑更正这些问题:)