-1
#include <stdio.h>
int main (){
int n = 8;
int vettore[n] = {15,3,6,2, 12,13,14,10};
printf("%d", vettore[0]);
}

It gives me the error:excess elements in array initializer int vettore[n] = {15,3,6,2 12,13,14,10}; Pls someone help me!

  • @anatolyg: This is not a duplicate of [that question](https://stackoverflow.com/questions/18848537/can-a-const-variable-be-used-to-declare-the-size-of-an-array-in-c). The reported compiler message asserts excess elements, not a variable array length. None of the current versions of GCC, Clang, and MSVC on Godbolt report such an error message for the code in the question, for either C or C++, so this is a probably reporting error by OP, not a duplicate question. – Eric Postpischil Oct 24 '22 at 13:51
  • The code in the question does not appear to produce the error message in the question. Check that you are compiling exactly that code and getting that error message. If there was a mistake, update the question with the code that gets the message. Also state the name and version of the compiler you are using and the command-line switches used to compile. – Eric Postpischil Oct 24 '22 at 14:10

1 Answers1

-1

In c array dimension declaration must be a constant but in your case it's a variable.

#include <stdio.h>
#define n 8 //define a constant
int main ()
{
    int vettore[n] = {15,3,6,2,12,13,14,10};

    printf("%d", vettore[0]);
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
fbc14
  • 1
  • 1
  • This does not explain the error message reported in the question. – Eric Postpischil Oct 24 '22 at 13:51
  • He got that error because he's using a variable to declare the dimension of an array. – fbc14 Oct 24 '22 at 14:24
  • No, using a variable to specify the dimension of an array should result in either a message that variable length arrays are not supported or a message that variable length arrays may not be initialized, depending on circumstances. Testing with GCC, Clang, and MSVC shows it does not result in a message “excess elements in array initializer”. – Eric Postpischil Oct 24 '22 at 14:27
  • Try it in codeblocks and you'll get it. – fbc14 Oct 24 '22 at 14:31