我在学校学习C,我要在课堂上制作一个程序,该程序接收文件并将信息存储到结构数组中,稍后使用该数组来确定是否有足够的库存可用。我尝试全局使用结构数组,并花了几个小时尝试将其传递到函数中并在 main 中声明它。但是,我仍然将分段错误视为错误,并且我不知道我的确切问题是什么。
typedef struct
{
char szStockNumber[7]; // Stock Number for a stock item
long lStockQty; // quantity in stock
double dUnitPrice; // price per unit of stock
char szStockName[31]; // name of the stock item
} Inventory;
#define MAX_INVENTORY 20;
void readWriteInventory(Inventory inventoryM[]);
int main(int argc, char *argv[])
{
char *pszOrderFileName = NULL;
char *pszInventoryFileName = NULL;
int rc;
Inventory inventoryM[MAX_INVENTORY];
readWriteInventory(inventoryM);
return 0;
}
void readWriteInventory(Inventory inventoryM[])
{
int iInventoryCnt = 0; // number of inventory items
char szInputBuffer[100];
char *pszGetsResult;
int iScanfCnt;
fprintf(stdout, "%-6s %-8s %-10s %-30sn", "Stock", "Quantity", "Unit Price", "Stock Name");
/* get inventory data until EOF
** fgets returns null when EOF is reached.
** store inventory in array
*/
pszGetsResult = fgets(szInputBuffer, 100, pfileInventory);
int i;
for(i = 0; i < MAX_INVENTORY; i++)
{
if (pszGetsResult != NULL)
{
iScanfCnt = sscanf(szInputBuffer, "%6s %8ld %10lf %30[^n]"
, inventoryM[i].szStockNumber
, &inventoryM[i].lStockQty
, &inventoryM[i].dUnitPrice
, inventoryM[i].szStockName);
// Check for bad input. scanf returns the number of valid conversions
if (iScanfCnt < 4)
exitError(ERR_INVALID_INVENTORY_DATA, szInputBuffer);
fprintf(stdout, "%6s %8ld %10.2lf %30sn"
, inventoryM[i].szStockNumber
, inventoryM[i].lStockQty
, inventoryM[i].dUnitPrice
, inventoryM[i].szStockName);
iInventoryCnt++;
if(iInventoryCnt > MAX_INVENTORY)
exitError(ERR_TOO_MANY_STOCK_ITEMS, szInputBuffer);
pszGetsResult = fgets(szInputBuffer, 100, pfileInventory);
}
else
break;
}
}
我要出去走走 - 如果你改变:
if(iInventoryCnt > MAX_INVENTORY)
自
if(iInventoryCnt >= MAX_INVENTORY)
这样,如果iInventoryCnt
等于 20,程序将不会尝试进入InventoryM
的第 20 个元素(这是越界的,因为 19 是最大值)。