未使用指针却触发‘表达式需为指针类型’编译错误求助
解决C++数组访问的类型错误问题
问题根源
错误的核心是命名冲突:
- 你先定义了
const int size = 100;,这里的size是一个整型常量; - 随后又尝试用
size作为数组名定义int size[size];,这会导致编译器混淆size的身份。当你在case 1中写size[numItems]时,编译器会把size识别为之前的整型常量,而非数组——而数组下标运算符[]要求操作数是指针或数组类型,对int值使用[]自然会触发类型错误。
解决方法
给存储物品尺寸的数组换个不冲突的名字,比如itemSize,然后同步修改所有访问该数组的代码即可。
修正后的代码片段
#include <iostream> using namespace std; int main() { const int size = 100; int code[size]; // 重命名数组,避免和常量size冲突 int itemSize[size]; int quantity[size]; float price[size]; int numItems = 0; do { int choice; cout << "Please select an option:" << endl; cout << "[1] Add a new item to the inventory" << endl; cout << "[2] Remove an item from the inventory" << endl; cout << "[3] Update the quantity of an existing item" << endl; cout << "[4] Update the price of an existing item" << endl; cout << "[5] Display the current inventory and the total value of the inventory" << endl; cin >> choice; switch (choice) { case 1: if (numItems < 100) { cout << "Enter the code: \n"; cin >> code[numItems]; cout << "Enter the size: \n"; // 同步修改为新的数组名 cin >> itemSize[numItems]; // 新增计数逻辑,记录已添加物品数量 numItems++; } // 可补充else分支提示库存已满 break; // 其他case逻辑可继续完善 } } while (choice != 0); // 假设0为退出选项,可按需调整 return 0; }
内容的提问来源于stack exchange,提问作者i227423 Hassan Ali
相关产品推荐
相关产品推荐

