1

I am writing a 2d matrix program.

Requirements for the assignment:

Implement the following functions:
float *allocate(int rows, int cols);
void readm(float *matrix, int rows, int cols);
void writem(float *matrix, int rows, int cols);
void mulmatrix(float *matrix1, int rows1, int cols1, float *matrix2, int cols2, float *product);

My code (some parts removed in main, just creating and calling allocate)

int main() {
float * matrix1;
float * matrix2;
matrix1 = allocate(rows1,cols1);
matrix2 = allocate(rows2,cols2);
}

float *allocate(int rows, int cols) {
    float ** matrix = new float *[rows * cols];
    return *matrix;
}//end allocate

void writem(float *matrix, int rows, int cols) {
    for (int x = 0; x < rows; x++) {
        for (int y = 0; y < cols; y++) {
            cout << "enter contents of element at " << (x + 1) << ", " << (y + 1) << " ";
            cin >> matrix[x*rows + cols];
        }
    }
}//end writem

I get an error

Exception thrown at 0x0FECF6B6 (msvcp140d.dll) in lab5.exe: 0xC0000005: Access violation writing location 0xCDCDCDD5. If there is a handler for this exception, the program may be safely continued.

It occurs at the line cin >> matrix[x*rows + cols];

sickachu
  • 11
  • 1
  • 2
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Mar 07 '17 at 14:29
  • 2
    The error indicates that you're dereferencing an uninitialized pointer. – πάντα ῥεῖ Mar 07 '17 at 14:32
  • Agreed this is an uninitialized heap pointer: http://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations/127404#127404 – drescherjm Mar 07 '17 at 14:44

1 Answers1

2

First of all you missed with indices. Should be cin >> matrix[x*rows + y]; instead of cin >> matrix[x*rows + cols];

Second why do you want to create matrix of float * instead of just float?

float *allocate(int rows, int cols) {
    float* matrix = new float[rows * cols];
    return matrix;
}//end allocate
JustRufus
  • 492
  • 1
  • 5
  • 10