I'd like to convert a Matrix into an array, which I managed to do inside the main function, but when time to come to put it in a function, it stops working and I get an access violation error which didn't show inside the main scope.
Here is the code, I need help to complete the conversion. I need to cast it from a class function for my project.
#include <iostream>
const int rows = 3, cols = 4; //define constant rows and columns
int* MatrixToArray(static int* matrix[rows][cols]) {
int* array[rows*cols]{};//initialize the array
int* ptrResult=nullptr;//initialize the return variable
//First loop to fill the matrix with dissociated values to print out
for (int i = 0; i < rows-1; i++) {
for (int j = 0; j < cols-1; j++) {
if (matrix) {
*matrix[i][j] = i + j + i * (j + cols); ///exception violation access memory
}
if (matrix) {//debug warning C6011
std::cout << " [" << *matrix[i][j] << "]";
}
}
std::cout << ",\n";
}
//second reversed loop to get the unified array from the previous matrix
for (int u = 0; u < 1; u++) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array) {//debug warning C6011
array[u] = matrix[i][j];
if (ptrResult) {//debug warning C6011
ptrResult = array[u];
}
}
std::cout << "[" << *array[u] << "] ";
}
}
}
free(array);
return ptrResult;
}
int main()
{
int* matrix[rows][cols];
std::cout << MatrixToArray(matrix);
}
After adapting the types for the matrix and the array, I get this code :
#include <iostream>
const int rows = 3, cols = 4; //define constant rows and columns
int* MatrixToArray(int** matrix) {
int* array[rows*cols]{};//initialize the array
int* ptrResult=nullptr;//initialize the return variable
//allocate memory as requested in the subedit comment field answers
matrix = new int* [rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
//First loop to fill the matrix with dissociated values to print out
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix) {
matrix[i][j] = i + j + i * (j + cols); ///exception violation access memory disappear
}
if (matrix) {//debug warning C6011
std::cout << " [" << matrix[i][j] << "]";
}
}
std::cout << ",\n";
}
//second reversed loop to get the unified array from the previous matrix
if (array) {
for (int u = 0; u < 1; u++) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array) {//debug warning C6011
array[u] = &matrix[i][j];
if (ptrResult) {//debug warning C6011
ptrResult = array[u];
}
}
//std::cout << "[" << *array[u] << "] ";
}
}
}
free(array);//File: minkernel crts ucrt src appcrt heap debug_heap.cpp Line:904 expression: _CrtlsValidHeapPointer(block)
}
return ptrResult;
}
int main()
{
//memory allocation correction
int** matrix;
matrix = new int* [rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
std::cout << MatrixToArray(matrix);
}
I still get an exception error, but in the assembly code which ends up into the message copied in the comment next to the line quoted.