更多的細節這是錯誤的:
if(storeMoreItems != NULL)
{
storeMoreItems = purchases;
purchases[i-1] = itemPrice;
}
首先,你覆蓋只是realloc
ED指針,你的意思是有
purchases = storeMoreItems;
有代替另一邊。但是這不會影響指針函數中傳入的指針所具有的值。
對於這一點,你需要從main
合格purchases
地址
double startShopping(double **purchases_ptr, double *taxAmount, double *subTotal, double *totalPrice)
,並指定
*purchases_ptr = storeMoreItems;
再分配本身,
storeMoreItems = (double*)realloc(storeMoreItems, i * sizeof(int));
使用錯誤鍵入計算分配的大小,即差不多當然也是非常錯誤的。
在main
:
size_t purchase_count = QUANTITY_SIZE;
double *purchases = malloc(purchase_count * sizeof *purchases);
// ...
startShopping(&purchases, &purchase_count, taxAmount, subTotal, totalPrice);
// ...
和startShopping
看起來像
double startShopping(double **purchases_ptr, size_t *purchase_count,
double *taxAmount, double *subTotal, double *totalPrice)
{
double itemPrice = 0.00;
double* purchases = *purchases_ptr;
size_t i;
for(i = 0; ; *subTotal += purchases[i++])
{
printf("Enter the price of the item :");
scanf("%lf", &itemPrice);
// I'm assuming you don't really want to add the -1
// entered for termination
if (itemPrice == -1) {
break;
}
if (i == *purchase_count) {
// array filled, let's get more space
// double it, or add a fixed amount,
// but rather not just one element each round
*purchase_count *= 2;
// we have the address saved in another variable, so here we can
// store the pointer returned by realloc in purchases without losing
// the handle if realloc fails
purchases = realloc(purchases, *purchase_count * sizeof *purchases);
if (purchases == NULL) {
// reallocation failed, now what?
// throw a tantrum?
free(*purchases_ptr);
exit(EXIT_FAILURE);
// or can something less drastic be done?
} else {
// Okay, got the needed space, let's record the address
*purchases_ptr = purchases;
}
}
purchases[i] = itemPrice;
}
// store the number of items actually read in?
*purchases_count = i;
// That should probably also get passed the number of items stored
displayCart(purchases);
*taxAmount = *subTotal * TAX_AMOUNT;
*totalPrice = *taxAmount + *subTotal;
printf("\nTotal comes to : $%.2lf\n", *totalPrice);
return *totalPrice;
}
感謝您指出了這一點,我只是糾正了。感謝您的解釋。 – theGrayFox
不客氣;) –
也請看Daniel的回答。他的通知也非常重要。記得給他+1;) –