3

Assume we have these declarations:

int** a;
int b[x][y];

Can I implement a function

foo f(bar c) {}

that lets me

f(a);
f(b);

without needing to overload it?

3
  • You could take a type that has two conversion constructors :p That kind of ruins the point, but it's not overloading that function. Commented Dec 2, 2012 at 0:04
  • I think if you understand the code a compiler generates for a multi-dimensional array reference, you can answer this yourself. For b[i][j] the compiler generates (b+iy+j) (or it might be (b+jx+i), I never remember). Either way function f() will not know the dimensions of b[][] so it could not properly handle references to c[i][j]. Commented Dec 2, 2012 at 0:08
  • 1
    These two types are not compatible, so no. Commented Dec 2, 2012 at 0:17

1 Answer 1

1

Sure, just use void* :)

And to answer your question, no. A multidimentional array is not the same as a pointer to a pointer. The reason is the indexing scheme. int b [2][2] is a continuous memory block of 4 integers. Indexing into it is equivalent to the following:

b[i][j] == *(b + 2*i + j)

The second dimension is part of the type defintion! The compiler knows that it only needs one dereference due to the memory layout of the array.

Meanwhile, for int** a the indexing is done like this:

a[i][j] == *(*(a+i)+j)
Sign up to request clarification or add additional context in comments.

2 Comments

Do we really need the dangerously misleading first line?
@LightnessRacesinOrbit, is it really misleading? I think it gets the point across that unless you want to give up all type information, you can't do what the OP asked about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.