The following function fails in the case of a call like:
CreateMatrix(A, 2,
1, 2,
3, 4);
but, passes in the case of a call like:
CreateMatrix(A, 2,
1.0, 2.0,
3.0, 4.0);
How can I make this function work in the case of integer arguments?
Source code:
void CreateMatrix(float* &A, int count, ...) {
A = (float*)malloc(count * count * sizeof(float));
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
A[i * count + j] = (float)va_arg(args, double); // Use "double" type parameter
}
}
va_end(args);
}
For example:
TEST(matrix_hpp_test, create_matrix_test)
{
float *A = nullptr;
CreateMatrix(A, 2,
1, 2,
3, 4);
ASSERT_EQ(A[0], 1);
ASSERT_EQ(A[1], 2);
ASSERT_EQ(A[2], 3);
ASSERT_EQ(A[3], 4);
}
Output:
C:\git\test_run.exe --gtest_color=no
Testing started at 5:00 PM ...
Running 1 calendar_tests from 1 calendar_tests suite.[----------] Global calendar_tests environment set-up.
[----------] 1 calendar_tests from matrix_hpp_test
C:/git/matrix_test.cpp:13: Failure
Expected equality of these values:
A[0]
Which is: 0
1.0
Which is: 1
[----------] 1 calendar_tests from matrix_hpp_test (0 ms total)
[----------] Global calendar_tests environment tear-down
1 calendar_tests from 1 calendar_tests suite ran. (0 ms total)[ PASSED ] 0 tests.
[ FAILED ] 1 calendar_tests, listed below:
[ FAILED ] matrix_hpp_test.create_matrix_test
1 FAILED TEST
Process finished with exit code 1
On the other hand,
TEST(matrix_hpp_test, create_matrix_test)
{
float *A = nullptr;
CreateMatrix(A, 2,
1.0, 2.0,
3.0, 4.0);
ASSERT_EQ(A[0], 1);
ASSERT_EQ(A[1], 2);
ASSERT_EQ(A[2], 3);
ASSERT_EQ(A[3], 4);
}
Output
C:\git\test_run.exe --gtest_color=no
Testing started at 5:04 PM ...
Running 1 calendar_tests from 1 calendar_tests suite.[----------] Global calendar_tests environment set-up.
[----------] 1 calendar_tests from matrix_hpp_test
[----------] 1 calendar_tests from matrix_hpp_test (0 ms total)
[----------] Global calendar_tests environment tear-down
1 calendar_tests from 1 calendar_tests suite ran. (0 ms total)[ PASSED ] 1 calendar_tests.
Process finished with exit code 0
Here is a template version:
template<typename T>
void CreateMatrix(T* &A, int count, ...) {
A = (T*)malloc(count * count * sizeof(T));
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
A[i * count + j] = va_arg(args, T);
}
}
va_end(args);
}
It also fails:
TEST(matrix_hpp_test, create_matrix_test)
{
float *A = nullptr;
CreateMatrix<float>(A, 2,
1, 2,
3, 4);
ASSERT_EQ(A[0], 1);
ASSERT_EQ(A[1], 2);
ASSERT_EQ(A[2], 3);
ASSERT_EQ(A[3], 4);
}
Output
C:\git\test_run.exe --gtest_color=no
Testing started at 5:34 PM ...
Running 1 calendar_tests from 1 calendar_tests suite.[----------] Global calendar_tests environment set-up.
[----------] 1 calendar_tests from matrix_hpp_test
Process finished with exit code -1073741795 (0xC000001D)