0

I was looking for a way to pass around fixed-size arrays in C, in such a way that the compiler can detect size errors, and I can use sizeof() on the array that is passed around. Choosing between wrapping the array in a struct and the pointer-to-fixed-size-array trick, I decided I liked the latter more than introducing yet another type in my code. The result was code similar to the example code below:

int myfunc(const char (*a)[128]) {
    return (*a)[0] == 0;
}

int main(void) {
    char arr[128] = { 0 };

    return myfunc(&arr);
}

However, gcc (4.9.2) complains about the const qualifier in myfunc():

test.c: In function ‘main’:
test.c:8:19: warning: passing argument 1 of ‘myfunc’ from incompatible pointer type
     return myfunc(&arr);
                   ^
test.c:1:5: note: expected ‘const char (*)[128]’ but argument is of type ‘char (*)[128]’
 int myfunc(const char (*a)[128]) {
     ^

clang (3.6.0) compiles without any complaints.

So my question: am I doing something illegal with adding this const qualifier? And if so, why is it illegal?

  • 3
    similar question: https://stackoverflow.com/questions/28701376/incompatible-pointer-types-and-constness – cremno Jul 26 '15 at 09:28
  • Thanks. The answer there does indeed answer my question. I guess I'll have to switch to using wrapper structs. – Steffan Karger Jul 26 '15 at 09:41
  • @SteffanKarger it answers your question. Is it invalid? Yes. Why? Your program violates the assignment operator constraints (for reference to the Standard see the quotes in the duplicate). – ouah Jul 26 '15 at 09:50

0 Answers0