Megan
Megan

Reputation: 129

Invalid conversion error with int arrays

I have an assignment to get command line arguments from a user - the user inputs two ints to define the rows and columns of a dynamic array. The array is then filled with random numbers. I can't seem to create the array, as I keep getting invalid conversion errors no matter what I try. Can anyone clear up what I'm misunderstanding here?

I've reproduced the relevant code and error message per line below:

int main(int argc, char* argv[]) {

/* Cut out code irrelevant to question that gets the arguments 
   to define columns and rows. This part works fine. */

    int * array = new int[rows];

    int i, j;
    for (i = 0; i < rows; i++) {
            array[i] = new int[columns];  // error: invalid conversion from ‘int*’ to ‘int’

    }

    int * pointer = array;

    array = randomArray(pointer, rows, columns);

    for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                    cout << array[i][j] + " " << endl;  // error: invalid types ‘int[int]’ for array subscript

            }
    }

    return 0;

}


int* randomArray(int array[], int rows, int columns) {

    srand (time(0));

    for (i = 0; i < rows; i++) {
            for (j = 0; j < columns; j++) {
                    int random = rand() % 100;
                    array[i][j] = random; // error: invalid types ‘int[int]’ for array subscript
            }
    }
    return array;

    for (i = 0; i < rows; i++) {
            delete[] array[rows];
    }
    delete[] array; // error: type ‘int’ argument given to ‘delete’, expected pointer
}

I've managed to clean up most of the errors so far but I can't seem to fix these last ones. I know I'm missing something important about 2d arrays. Any tips?

Upvotes: 0

Views: 987

Answers (1)

simonc
simonc

Reputation: 42165

You want array to be an array of pointers to int arrays so

int * array = new int[rows];

should be

int ** array = new int*[rows];

and

int* randomArray(int array[], int rows, int columns)

would become

int** randomArray(int *array[], int rows, int columns)

or, as pointed out by WhozCraig,

void randomArray(int *array[], int rows, int columns)

since the return value isn't required.

Alternatively, if it doesn't violate constraints of your assignment, you could use std::vector instead

std::vector<std::vector<int>> array;

Upvotes: 3

Related Questions