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

标签 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;
}

我查看了该网站上的一些其他答案,但似乎没有一个可以帮助我解决我的问题。我有一种沉闷的感觉,答案就在我的脸上,但作为一个疲惫的业余程序员,我一直无法找到它。提前致谢!

最佳答案

有两种价格 一种是for循环内的数组,另一种是循环外的int。因此,当您尝试在最后打印它时,价格 [num_bottles] 不再存在,其中只有 int 价格。显然,int 价格不能用作prices[index2]

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

关于C:下标值既不是数组也不是指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9882285/

相关文章:

java - 如果我们超出了Java中ByteBuffer.allocate(48) NIO包类中分配缓冲区的容量怎么办

自定义 Eclipse 代码辅助

c - 为什么 strcat 连接两个字符串失败?

c - 在没有表模式的情况下将 CSV 导入 SQLite

c - mplab xc8/16 builtin_constant_p

c++ - 带有 C++ 的 Lua 脚本 : attempt to index global 'io' (a nil value)

javascript - 有没有办法使用数组来简化代码?

java - 不可变数组的修改不起作用

javascript - 谷歌地图 : place ID array over 10 doesn't work

io - 通过 ynot 在 Coq 中进行文件 I/O