更多的细节这是错误的:
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;) –