Passing an array to a function by reference/pointers

O

Ohmu

Hi!

How to pass an (multidimensional)array of something to a function with
reference/pointer?

Can anyone help me with that?

Thanks,
Ohmu
 
J

John Harrison

Ohmu said:
Hi!

How to pass an (multidimensional)array of something to a function with
reference/pointer?

Can anyone help me with that?

Thanks,
Ohmu

Here's how to prototype and call functions with arrays, references and
pointers.

// one dimension with pointer
void function(int *a);
int array[10];
function(array);

// two dimensions with pointer
void function(int (*a)[20]);
int array[10][20];
function(array);

// three dimensions with pointer
void function(int (*a)[20][30]);
int array[10][20][30];
function(array);


// one dimension with reference
void function(int (&a)[10]);
int array[10];
function(array);

// two dimensions with reference
void function(int (&a)[10][20]);
int array[10][20];
function(array);

// three dimensions with reference
void function(int (&a)[10][20][30]);
int array[10][20][30];
function(array);

john
 
O

Ohmu

John Harrison said:
Here's how to prototype and call functions with arrays, references and
pointers.

// one dimension with pointer
void function(int *a);
int array[10];
function(array);
// one dimension with reference
void function(int (&a)[10]);
int array[10];
function(array);

but how to pass the array when the size is read from file, int array[size][size] ??

Ohmu
 
J

John Harrison

Ohmu said:
"John Harrison" <[email protected]> wrote in message
Here's how to prototype and call functions with arrays, references and
pointers.

// one dimension with pointer
void function(int *a);
int array[10];
function(array);
// one dimension with reference
void function(int (&a)[10]);
int array[10];
function(array);

but how to pass the array when the size is read from file, int array[size][size] ??

Ohmu

int array[size][size]; is not a legal array declaration.

If your 2d array is dynamic then you need to allocate some memory for it and
use pointers. E.g.

void function(int** a);

int **array;
array = new int*[size];
for (int i = 0; i < size; ++i)
array = new int[size];
function(array);

This question is in the FAQ

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.15

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top