简体   繁体   中英

How to write a 2d-array C++ function-parameter (eg. for int[x][y])?

I have an 2D-Array

int tilemap[800][600];

I want to use such an Araay in an Function (as parameter)

void load(int* tiles);

But the datatype int* is not the right one.

What is the right one? I have no idea.

Thanks!

void load(int tiles[][600]);

You can have matrix in two ways. One is using pointer to array of pointers (rows) to array of data.

Other way is the way you have chosen. It's, as you sad, a 2-D array, which means that (in case of c/c++) rows of data are one behind of other in memory. This matrix:

 +-------+
 | 7 | 9 |
 +-------+
 | 5 | 2 |
 +-------+

is represented like this in memory:

[ [7] [9] ] [ [5] [2] ]

To get element at position [1][0], computer needs to calculate it's address from address of matrix (the address of it's first element) and position numbers. In the above example you see that address of [1][0] is (address of number 7) + 2*sizeof(int), that is &matrix + 2. So the actual formula to calculate address of element [i][j] is

&matrix + (number_of_columns*i + j)

I omitted *sizeof(int) or *sizeof(type) because arithmetic that includes pointer and integer already includes that, but if &matrix is raw address to some data, without knowledge of it's type it should be included. That's what happens at level of machine instructions, computer calculates

 address_of_matrix + (number_of_columns*i + j)*sizeof(type)

So you need to tell compiler at least what is number of columns this matrix has. You'll also need number of rows of course, but that's something you need, not compiler.

I hope it's clearer. It's hard to explain it here. But there are a lot of material on the net.

the datatype int* is not the right one.

Actually, it is just fine. An array of arrays has all elements stored sequentially, so a pointer to the first is sufficient to find all the others.

The "best" option, though, is a reference-to-array-of-array, because that will preserve the size information:

template<size_t M, size_t N>
void load(int (&tiles)[M][N])
{
}

(Note that like all templates, the definition should be visible at the point of instantiation)

If the second extent is always fixed, you can pass an array-of-array as pointer-to-array, because array-of- T can always be passed as pointer-to- T :

void load(int (*tiles)[600])
{
}

This is what both Marko and 2501's example code is doing, although they are using a misleading syntax that looks like an array, while in fact it is a pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM