简体   繁体   中英

Why can't I initialize my array?

All I'm trying to do is initialize my array to all 0s in C, but my compiler keeps giving me errors (and the errors aren't helpful). The array has 24 entries and the values are floating point values.

main()
{

/* Array of users arrival & departure time */
float user_queue[24];

/* Initialize queue to 0 */
int i;
for(i = 0; i < 24; i++)
{
    user_queue[i] = 0.0;
}

/* Simulation time */
float time = 0;

The compiler is giving me an error on the "float time" line. The error goes away if I remove my for loop.

syntax error : missing ; before type

You may not be allowed to declare variables after you have already used expressions. Try moving the declaration of time to the top:

main()
{

/* Array of users arrival & departure time */
float time, user_queue[24];

/* Initialize queue to 0 */
int i;
for(i = 0; i < 24; i++)
{
    user_queue[i] = 0.0;
}

/* Simulation time */
time = 0;

You're overrunning the array by 1 element. Try this instead:

for(i = 0; i < 24; i++)

Change the <= to < .

EDIT : With new information.

You're probably compiling in C89/90 or ANSI C mode. In those older C revisions, variable declarations must be at the start of the function or scope. You can't intermingle declarations and code like that.

Try this:

main()
{

    /* Array of users arrival & departure time */
    float user_queue[24];

    float time;  /* Declare up here */

    /* Initialize queue to 0 */
    int i;
    for(i = 0; i < 24; i++)
    {
        user_queue[i] = 0.0;
    }

    /* Simulation time */
    time = 0;

For this you don't even need a loop:

/* Array of 24 users */
float user_queue[24] = { 0.0 }; 

this will initialize the array to all zeros without the for loop.

< , not <= , thus:

for( i = 0; i < 24; i++ )

When you create an array like this:

float user_queue[24]

You are creating an array with 24 elements, numbered 0 through 23.

With respect to your updated code, float time = 0; needs to come at the beginning of the main(){.....} block. C's prior to C99 (with the exception of some implementations) didn't let you declare variables except at the beginning of their enclosing scope/block.

这样做:

float user_queue[24] = {0};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM