8

Consider following declaration:

int a[M][N]; // M and N are known compile-time

Would it be legal to treat it like as it was declared as:

int a[N][M];

or even:

int a[A][B]; // where A * B = M * N

in C without breaking its rules (badly)?

I found that it can be acomplished without any cast:

#include <stdio.h>

void print_array(int a[][2], int n);

int main(void)
{
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};

    //int (*p1)[2] = a; // compile error

    int (*ptr_temp)[] = a; // pointer to array of incomplete type
    int (*p2)[2] = ptr_temp; // compiles without any warning

    print_array(p2, 3);
}

void print_array(int a[][2], int n)
{
    for (int i = 0; i < n; i++)
        for (int j = 0; j < 2; j++)
            printf("a[%d][%d] = %d\n", i, j, a[i][j]);
}

Notice that we cannot assign a to p1 pointer directly. However compiler does not complain when p2 is assigned with ptr_temp even if it seems to be potentially dangerous (it does not require any cast for that). Is it really sanitized? If so, then why it disallows the first assignmment?

5
  • 2
    No, it is not permitted. The existence of a conversion path consisting entirely of legal implicit conversions says nothing about the validity of performing arithmetic on, or dereferencing, such pointers. Keep in mind you can make nearly arbitrary implicit conversion paths with pointers to void. Commented Jul 15, 2015 at 23:55
  • 1
    Lack of a compiler error when stepping through an intermediate pointer type doesn't necessarily mean the world is right. A simple intermediate void* (or even a cast) would accomplish the same lack-of-errors in C. Commented Jul 15, 2015 at 23:55
  • 1
    I'm not so sure about your specific code, but I believe print_array( (int(*)[2])&a , 3); would be legal. The standard is not precisely clear with regarding accessing arrays via a cast to different array type. Commented Jul 16, 2015 at 1:18
  • @R.. could you please elaborate this into an answer? I am ok with the fact that the conversion alone doesn't tell anything about validity. But it doesn't tell anything about invalidity, either. Commented Jul 16, 2015 at 6:16
  • I think it's legal according to the C standard but it's such an awful idea that it's moot and not worth the time to do the language lawyering to determine a definitive answer. Commented Jul 16, 2015 at 6:38

1 Answer 1

1

The behavior you see is because of the way multidimensional arrays are handled in C.

Have a look at this question Pointer address in a C multidimensional array

Sign up to request clarification or add additional context in comments.

Comments

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.