簡體   English   中英

為什么我不能初始化我的數組?

[英]Why can't I initialize my array?

我所要做的就是將我的數組初始化為C中的所有0,但我的編譯器一直給我錯誤(並且錯誤沒有幫助)。 該數組有24個條目,值是浮點值。

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;

編譯器在“浮動時間”行上給出了一個錯誤。 如果我刪除for循環,則錯誤消失。

語法錯誤:缺失; 在類型之前

在使用表達式后,可能不允許聲明變量。 嘗試將time宣告移至頂部:

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;

你用1個元素超越了數組。 試試這個:

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

<=更改為<

編輯:有了新的信息。

您可能正在使用C89 / 90或ANSI C模式進行編譯。 在那些較舊的C版本中,變量聲明必須位於函數或范圍的開頭。 你不能將聲明和代碼混合在一起。

嘗試這個:

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;

為此你甚至不需要循環:

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

這將在沒有for循環的情況下將數組初始化為全零。

< ,而不是<= ,因此:

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

當您創建這樣的數組時:

float user_queue[24]

您正在創建一個包含24個元素的數組,編號為0到23。

關於更新的代碼, float time = 0; 需要來到main(){.....}塊的開頭。 在C99之前的C(除了一些實現之外)並沒有讓你聲明變量,除了在它們的封閉范圍/塊的開頭。

這樣做:

float user_queue[24] = {0};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM