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

88
Visualizações
Reusing variable in function parameter list
int doSomething(int n, int arr[n])

What confuses me here is the reusing of the n variable inside the parameter list. Can anyone explain why this is valid and what are the use cases?

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

0

C allows several syntaxs for passing an array pointer including:

 int* arr, int arr[] or int arr[10]  

However ALL of these are equivalent to the first - that is the compiler sees only an int pointer and does not use any size that may have been specified in the array square brackets to enforce integrity on the size of the array passed. In all the above cases the compiler will generate:

void __cdecl foo(int * const)

The only way to specify the size of an array is, as you have done, pass a separate parameter indicating the size/length of the array.
In the example you cite the n in arr[n] is not used by the compiler to maintain any integrity on the array bounds - in the example it is only included as an indication that the first parameter is the size. A less controversial form of the same code might be just to state that more explicitly:

int doSomething(int arr_len, int arr[])

In terms of what is the best convention or preference for passing an pointer and its array size see this question.

over 4 years ago · Santiago Trujillo Relatório

0

It is valid.

For this specific case it is equivalent to:

int doSomething(int n, int arr[]);
int doSomething(int n, int *arr);

because the array parameters are automatically transformed into pointers to arrays' elements. In general there are a few differences between array-like and pointer declarations of parameters. See link for more details.

IMO, the better usage should be:

int doSomething(int n, int arr[static n]);

This static n tell the compilers that at least n elements pointer by arr are valid. Moreover it makes the declaration visually different from a declaration of array what helps to avoid surprising issues when sizeof arr is used.

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