Haoest
Haoest

Reputation: 13906

How to cast dynamic array to static array in c++?

In c++ how do you cast a dynamic array to static?

Say

I have

int ** da;
da = new int*[9];
for (int i=0; i<9; i++) da[i] = new int[9];

and my function argument is of type int[9][9], how do I cast da so my function can use it?

Upvotes: 0

Views: 3643

Answers (3)

ygao
ygao

Reputation: 102

It may not relate to this question. But it reminds me a trick in matrix using C. The good part is we only need to call malloc and free once. The bad part is.....

// create the buffer and assign the pointer array
int  i, j;
int* buffer = (int*) malloc(sizeof(int) * 81);

int* matrix[9]; // 9 * 9
for (i = 0; i < 9; ++i)
    matrix[i] = buffer + i * 9;

// assign some value using matrix[i][j]
for (i = 0; i < 9; ++i)
    for (j = 0; j < 9; ++j)
        matrix[i][j] = (i + 1) * (j + 1);

// retrieve the value in matrix
for (i = 0; i < 9; ++i)
    for (j = 0; j < 9; ++j)
        std::cout << matrix[i][j] << " ";

std::cout << std::endl;

// free the buffer
free(buffer);

Upvotes: 0

justin
justin

Reputation: 104698

you don't - you must move as necessary if function keeps its signature. example:

void function(int a[9][9]);

int tmp[9][9];

// move to temp
for (size_t i(0); i < 9; ++i) {
    for (size_t j(0); j < 9; ++j) {
        tmp[i][j] = da[i][j];
    }
}

function(tmp);

// move to da
for (size_t i(0); i < 9; ++i) {
    for (size_t j(0); j < 9; ++j) {
        da[i][j] = tmp[i][j];
    }
}

the reason: the layout and alignment of 2D arrays is explicitly defined, and implementation defined. the function's implementation expects the exact layout and alignment. any other layout would obviously introduce a bug.

even int tmp[9*9] is not guaranteed to be the same as int tmp[9][9].

fortunately, creating this on the stack and copying to/from is cheap.

Upvotes: 1

Erik
Erik

Reputation: 91300

An int[9][9] is 81 integers consecutive in memory, taking 81*sizeof(int) bytes. An int *[9] is a sequence of 9 pointers to integer, taking 9*sizeof(int *) bytes. Each of these are setup to point to 9 distinct sequences of 9 ints.

You cannot use one in place of the other - no casting will change that these two are laid out completely different in memory.

Upvotes: 10

Related Questions