1

In line 6 it appears that int variable-sized object may not be initialized, what is the problem with the int? How can i fix it?

#include <stdio.h>
int main (void)
{
    const int SIZE=5;
    //variable remain constant
    int grades[SIZE]= {66,50,93,67,100};
    double sum= 0.0;
    int i;
    
    printf("\nMy grades are:\n");

    for (i=0;i<SIZE;i++)//0 first character and < because last character is sentinel
        printf("%d\t",grades[i]);

    printf("\n\n");
    for (i=0;i<SIZE;i++) //analyze data in list and retrieve it
        sum=sum+grades[i];
    
    printf("My average is %.2f\n\n",sum/SIZE); //sum /size for average with decimals
    return 0;
}

I expected to find an average using simple one-dimensional array, but that problem doesn't let me run the program

  • What makes you think that? Did you confirm with a debugger? – tadman Jan 03 '23 at 17:06
  • What does "doesn't let me run the program" mean in *technical terms*, such as error messages? – tadman Jan 03 '23 at 17:06
  • 4
    `int grades[SIZE]` defines a variable-length array, as `const int SIZE` is not considered a compile time expression (for defining the size of an array). A simple solution would be to change `SIZE` into a `#define SIZE 5` or an `enum{ SIZE = 5 }` – UnholySheep Jan 03 '23 at 17:07
  • Please [edit] your question to include more details about the problems you have with the shown code. If you get build errors, then please copy-paste (as text) the full and complete build log into the question. – Some programmer dude Jan 03 '23 at 17:08
  • Also please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Jan 03 '23 at 17:08
  • Thanks @UnholySheep, it worked with enum{ SIZE = 5 }. However I still don't understant the thing about variable-length array, can you give me any resource, website, or link to the platform to understand my error? Thanks. – Rubén Figueroa Jan 05 '23 at 05:27

1 Answers1

3

SIZE is not a constant.

SIZE is a const int, but, as strange as it sounds, it is still not a constant. grades[SIZE] is a variable length array. Variable length arrays may not be initialized. *1

const int SIZE=5;
int grades[SIZE]= {66,50,93,67,100};// error: variable-sized object may not be initialized

Alternate 1: Use a constant

5 is a constant of type int.

#define SIZE 5
int grades[SIZE]= {66,50,93,67,100};

Alternate 2: Promptly assign

Assign or copy in the values from some source, perhaps from a compound literal.

const int SIZE=5;
int grades[SIZE];
               v-----------------------v compound literal
memcpy(grades, (int []){66,50,93,67,100}, sizeof grades);

*1 Perhaps a future version of C will allow this.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256