Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing a constant matrix
    text
    copied!<p>Referring to <a href="https://stackoverflow.com/questions/546860/passing-arrays-and-matrices-to-functions-as-pointers-and-pointers-to-pointers-in">this</a> question and especially the accepted <a href="https://stackoverflow.com/questions/546860/passing-arrays-and-matrices-to-functions-as-pointers-and-pointers-to-pointers-in/546982#546982">answer</a> of litb, I wonder why the gcc complain about this:</p> <pre><code>void func(const int (*ip)[3]) { printf("Value: %d\n", ip[1][1]); } int main() { int i[3][3] = { {0, 1, 2} , {3, 4, 5}, {6, 7, 8} }; func(i); return 0; } </code></pre> <p>If I eliminate the <code>const</code> the compiler keeps still. Did I something misunderstand? I wanted to be sure that <code>func</code> don't modify my array.</p> <p><b>EDIT:</b> The same thing happens if I define a data type for my matrix:</p> <pre><code>typedef int Array[3][3]; void func(const Array *p) { printf("Value: %d\n", (*p)[1][1]); } int main() { Array a = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8} }; func(&amp;a); return 0; } </code></pre> <p>I accept, this kind of code isn't very C style, more like C++. In C++ indeed there would be no problem if I define Array as a class containing all the matrix behavior.</p> <pre><code>class Array {...}; </code></pre> <p>I suppose, I didn't understand very well the concept of arrays and arrays of arrays in C and passing them to functions. Any enlightenment?</p> <p>Thank you in advance.</p> <p><b>EDIT2:</b> Meanwhile I chewed a bit on this problem and it seems to converge to the following question: C/C++ implicitly converts a pointer to an <code>int</code> to a pointer to an <code>const int</code>. Thus the following works:</p> <pre><code>func(const int a[]) // aquivalent: func(const int *a) { ... } int main() { int b[10]; func(b); return 0; } </code></pre> <p>But C/C++ don't implicitly converts a pointer to an array of n <code>int</code>s to a pointer to an array of n <code>const int</code>s. Even though an array of n <code>int</code>s is implicitly converted to an array of n <code>const int</code>s. This level of indirection in the implicit conversion isn't supported. The following will be rejected (at least with a warning in C):</p> <pre><code>func(const int a[][n]) // aquivalent: func(const int (*a)[n]) { ... } int main() { int b[m][n]; func(b); return 0; } </code></pre> <p>It's similar to the problem that C++ doesn't implicitly convert a template for the type A into a template of type B even if A can be implicitly converted to B. The two templates are of completely different types.</p> <p>Is this the right answer?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload