[英]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.