簡體   English   中英

C:下標值既不是數組也不是指針

[英]C: Subscripted value is neither array nor Pointer

我正在為C類簡介做一些家庭作業,在其中我們必須編寫一個程序來讀取文本文件中的輸入,該文本文件包含來自釀酒廠的訂單信息。 我已經寫完了所有內容,但是當我運行它時,唯一可以正確打印的是“ Winery#1:”,然后窗口錯誤了。 我試圖在程序結尾打印出一個數組,以查看問題所在,然后出現一個錯誤,指出:

|54|error: subscripted value is neither array nor pointer|

我知道該錯誤意味着什么,盡管我不確定該如何糾正。 我相信我已經正確聲明了我的數組之類,但是我仍然收到錯誤。 這是我的代碼:

int main () {
  //Creates the file pointer and variables
  FILE *ifp;
  int index, index2, index3, index4;
  int wineries, num_bottles, orders, prices, sum_order, total_orders;

  //Opens the file to be read from.
  ifp = fopen ("wine.txt", "r");

  //Scans the first line of the file to find out how many wineries there are,
  //thus finding out how many times the loop must be repeated.
  fscanf(ifp, "%d", &wineries);

  //Begins the main loop which will have repititions equal to the number of wineries.
  for (index = 0; index < wineries; index ++) {
    //Prints the winery number
    printf("Winery #%d:\n", index + 1);

    //Scans the number of bottles at the aforementioned winery and
    //creates the array "prices" which is size "num_bottles."
    fscanf(ifp,"%d", num_bottles );
    int prices[num_bottles];

    //Scans the bottle prices into the array
    for (index2 = 0; index2 < num_bottles; index2++)
      fscanf(ifp, "%d", &prices[index2]);

    //Creates variable orders to scan line 4 into.
    fscanf(ifp, "%d", &orders);

    for(index3 = 0; index3 < orders; index3++){
      int sum_order = 0;

      for(index4 = 0; index4 < num_bottles; index4++)
        fscanf(ifp, "%d", &total_orders);

      sum_order += (prices[index4] * total_orders);
      printf("Order #%d: $%d\n", index3+1, sum_order);
    }
  }
  printf("%d", prices[index2]);
  fclose(ifp);
  return 0;
}

我查看了本網站上的其他一些答案,但似乎沒有一個對我的問題有所幫助。 我下沉的感覺是答案正看着我,但是我是一個累了的業余編碼員,我一直找不到。 提前致謝!

prices有兩種:一種是在for循環內的數組,另一種是在循環外的int。 因此,當您嘗試在最后打印int價格時, prices[num_bottles]不再存在。 顯然,int價格不能用作prices[index2]

從for循環中取出價格並將其放在頂部。

更改

//Scans the number of bottles at the aforementioned winery and
//creates the array "prices" which is size "num_bottles."
fscanf(ifp,"%d", num_bottles );

//Scans the number of bottles at the aforementioned winery and
//creates the array "prices" which is size "num_bottles."
fscanf(ifp,"%d", &num_bottles );
//               ^

暫無
暫無

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

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