-4
#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

Why output from InitializingMatrix and Output have differences?

How to fix it?

fzyier
  • 103
  • 5

1 Answers1

1

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
SimplyCode
  • 318
  • 2
  • 9