orlp
orlp

Reputation: 117981

Weird incompatible pointer type error

I have this seemingly innocent piece of code:

void generate_heightmap(float **terrain) {

}

int main(int argc, char **argv) {
    float terrain[1500][1500];

    generate_heightmap(terrain);

    return 0;
}

But when I try to compile it I get these weird errors, what could be the cause of this?

test.c||In function ‘main’:|
test.c|8|warning: passing argument 1 of ‘generate_heightmap’ from incompatible pointer type [enabled by default]|
test.c|1|note: expected ‘float **’ but argument is of type ‘float (*)[1500]’|
||=== Build finished: 1 errors, 1 warnings ===|

I have GCC 4.6.1 and Ubuntu 11.11 64bit.

Upvotes: 2

Views: 637

Answers (2)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

A 2D array is not compatible with a double pointer (consider how a 2D array is laid out in memory, and how indexing into it requires knowledge of one of the dimensions).

This precise topic is dealt with at Question 6.18 of the C FAQ.

Upvotes: 5

cnicutar
cnicutar

Reputation: 182774

Try something like this:

void generate_heightmap(float terrain[][1500]) 

There's also a C FAQ on the subject. Basically you're able to pass arrays to functions as pointers because they decay to a pointer. But they don't decay recursively.

It makes sense if you think what terrain[2] means for example. It means the third element of terrain: to obtain the address: terrain_addr + 2 * element_size.

So it's obvious at this point you need to know how large a terrain[x] object is.

Upvotes: 3

Related Questions