Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
Is "reformat" of multi-dimensional array by pointer to incomplete array type allowed in C?

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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda