函数传递的数组值错误

时间:2018-09-12 20:41:15

标签: c googletest

因此,我阅读了其他一些涵盖此内容的线程。他们注意到它是动态的,因此您需要分配该内存。当我分配这个空间然后放在我的值中时,问题是现在没有我的内存被保存到数组中。我想知道我是在分配错误还是对数组和c有误解?

//.c file
int *multiply(int m, int n, int *matrix, int *vector,int sizeV){
    int *final = (int*) malloc(sizeof(int)*n);
    int i = 0;
    int j = 0;
    int row = 0;
    int column = 0;

    if(n != sizeV){return NULL;};

    for(i = 0;i < sizeV;i++)
    {
            while(column < n)
            {
                    final[i] += matrix[row] * vector[column];
                    row++;
                    column++;
            }
            column = 0;
            j = 0;
    }
    for(i = 0;i < sizeV;i++)
    {
            printf("\nfinal[%d] = %d\n",i,final[i]);
    }
    return final;
}

googletest     //.googletest文件

TEST(MultiplyTest, Correct_Result_3x3){
int matrix[] = {1,2,3,4,5,6,7,8,9};
int vector[] = {1,2,3};
int correct[] = {14, 32, 50};   
int *result = multiply(3,3,(int *)matrix, vector,3);

ASSERT_NE(-1, *(result));

for(int i = 0; i < 3; i++)
    EXPECT_EQ(correct[i], *(&result[i]));   
}

TEST(MultiplyTest, Correct_Result_2x2){
    int matrix[] = {1,2,4,5};
    int vector[] = {1,2,};
    int correct[] = {5, 14};    
    int *result = multiply(2,2,(int *)matrix, vector,2);

     ASSERT_NE(-1, *(result));

    for(int i = 0; i < 2; i++)                  
        EXPECT_EQ(correct[i], *(result + i));   
    }

输出     //输出     [RUN] MultiplyTest.Correct_Result_3x3

final[0] = -1656784906

 final[1] = 32620

 final[2] = -1656784870
 src/Matrix-vector_unittests.cpp:15: Failure
 Expected equality of these values:
 correct[i]
 Which is: 14
 *(&result[i])
 Which is: -1656784906
src/Matrix-vector_unittests.cpp:15: Failure
Expected equality of these values:
 correct[i]
 Which is: 32
 *(&result[i])
 Which is: 32620
src/Matrix-vector_unittests.cpp:15: Failure
Expected equality of these values:
  correct[i]
  Which is: 50
 *(&result[i])
 Which is: -1656784870
[  FAILED  ] MultiplyTest.Correct_Result_3x3 (0 ms)
[ RUN      ] MultiplyTest.Correct_Result_2x2

final[0] = -1656784931

final[1] = 32602

src/Matrix-vector_unittests.cpp:27: Failure
Expected equality of these values:
 correct[i]
 Which is: 5
 *(result + i)
Which is: -1656784931
src/Matrix-vector_unittests.cpp:27: Failure

这些值的预期相等性:

同样,我不确定自己做错了什么。我目前不释放内存。我主要是想立即获取这些正确的值,并以此解决问题。

0 个答案:

没有答案