Passing Dynamically Allocated array in function

In a program I'm working on now, i need a milti-dimensional array. To save space, I used dynamically allocated array by using pointers, something like this-
int *arr;
arr=new int[col*row];

And now i need to pass this array in a function. Can anyone tell me the parameteres in the function declaration statement and at the function call statement?
It's std::vector<int> arr(col*row);, and, consequently, the function could be return_type function_name(const std::vector<int>& argument).
Although it may be simpler to use a matrix or multi-dimensional array library for this sort of thing.

I havn't done vectors yet, and the process seems different from that of array's. Although i tried doing according to you, but didnt work out.
in the function declaration i coded void straight(int arr[][]), and at the function call straight(arr);. But it is showing error!
You have declared a 1-d array with
1
2
int *arr;
arr=new int[col*row];

You can pass a pointer and the dimensions to a function like so:
return_type function_name(int* a, int rows, int cols).
but you would not be able to use [][] on the array. Instead of a[i][j] it would be a[i*cols+j].

If you need to use 2 indexes then setup a 2d array with:
1
2
3
int **arr=new int*[row];
for( int i=0; i<row; ++i)
    arr[i] = new int[col];

Pass as:
return_type function_name(int** a, int rows, int cols).
Reference in function as a[i][j]

Cleanup is:
1
2
3
for( int i=0; i<row; ++i)
    delete [] arr[i];
delete [] arr;
I tried using the first process you told, i.e using (int* a,int row,int col). But there is an error in each line of the function whwre i have used the array. And yes I've used in the form a[i*col+j] coz that is the way to access a dynamically allocated array. The error says-error: invalid types ‘int[int]’ for array subscript|
Topic archived. No new replies allowed.