C:下标值既不是数组也不是指针

时间:2012-03-27 01:44:14

标签: c arrays io

我正在做一些关于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;
}

我看了一下这个网站上的其他一些答案,但似乎没有一个能解决我的问题。我得到了沉闷的感觉,答案是看着我的脸,但作为我累的业余编码器,我一直无法找到它。提前谢谢!

2 个答案:

答案 0 :(得分:1)

有两个prices一个是for循环中的数组,另一个是循环外的int。所以当你试图在最后打印它时prices[num_bottles]不再存在,那里只有int价格。显然,int价格不能用作prices[index2]

从for循环中取出价格并将其放在顶部。

答案 1 :(得分:0)

更改

//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 );
//               ^