Odgrujahad
Odgrujahad

Reputation: 9

Why 2D arrays using pointers gives false values?

Started my adventure with programing fairly recently so please dont be too harsh.

I planed to create a 2D array that is filled with 0 (ultimately I will fil it with various numbers but not important right now). The size of array should be input by user. So I use pointers. I found some of the examples here on StackOverflow, tried using it and the code was buggy - sometimes it worked, sometimes it didnt.

It never works when rows = columns. It also never works when with second iteration of code You switch columns with rows eg:

Run code first time - call rows 3, columns 9, end program.

Run code second time - call rows 9, columns 3 - no execution.

Source I was using:Declaring a pointer to multidimensional array and allocating the array

#include <iostream> 

using namespace std;

void dynamicArray(int** array, int columns, int rows)

{
    
cout << " i am working" << endl;

        for (int i=0; i<rows ; ++i)
        {
            for (int j=0; j <columns ;j++)
            {
                array [columns][rows] = 0;
                cout << array [columns][rows] << "  "  << flush ;
            }
            cout << endl;
        }

}

int main() {

    int columns = 0;
    int rows = 0;
    cout << " state the number of rows: " << endl;
    cin >> rows;
    cout << " state the number of columns: " << endl;
    cin >> columns;

        int **array = new int*[rows];                   
        for(int i = 0; i < rows; ++i)
        {
            array[i] = new int[columns];
        }

        dynamicArray(array, columns, rows);

        for(int l = 0; l < rows; l++)

        delete [] array[l];
        delete [] array;

        return 0;

    }

I quite frankly have no idea how to fix it, hope for your help

BR, Mark

Upvotes: 0

Views: 53

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Generally using the size as the index can lead to out-of-range access.

Also the order of rows and columns looks swapped.

array [columns][rows] in the function dynamicArray should be array[i][j].

Upvotes: 4

Related Questions