Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two different outputs from functions

#include <iostream>
#include <iomanip>
#include <ctime>

using namespace std;

char* InitializingMatrix(char start, char end) {
    char matrix[9];

    //Initializing random symbols to char massive
    srand((unsigned)time(0));
    for (int i = 0; i < 9; i++)
        matrix[i] = (int)start + rand() % (int)end;

    //Output matrix
    for (int i = 0; i < 9; i++)
        (i == 3 || i == 6) ? cout << endl << (char)matrix[i] << " " : cout << (char)matrix[i] << " ";
    cout << endl;

    return matrix;
}

void Output(char matrix[]) {
    //Output matrix
    for (int i = 0; i < 9; i++)
        (i == 3 || i == 6) ? cout << endl << (char)matrix[i] << " " : cout << (char)matrix[i] << " ";
}


int main() {
    Output(InitializingMatrix('1', '6'));
    return 0;
}

Problem

The output of the matrix from the function for initializing the matrix and from the function for outputting the matrix are different.

Questions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why output from InitializingMatrix and Output have differences?

How to fix it?

>Solution :

The issue that you return a Pointer but you allocate a Value.

Allocation:

char matrix[9];

Return value:

char* InitializingMatrix(...)

Type char matrix[] is a compiled time array.
If you wish to use arrays you’ll need to use new char() instead to dynamically allocate a new array.

The C++ OOP way is to use a class:

  1. Use the built in type std::array<...>
  2. Create a class and save the array in there:
struct MyData 
{
  char Data[10];
}

The compiler would help you pass this around by value or use a ref to pass it by reference instead:

MyData Initialize() { ... };

void Output(MyData& data);
//or
void Output(const MyData& data);

int main() 
{
    MyData data = Initialize();
    Output(data );
    return 0;
}
  1. The more professional way is to use built-in types or frameworks that exist,
    If you need a matrix you can use libraries like GMTL or EIGEN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading