可能重复:
对数组使用动态内存分配
我最初有这个程序商店的价格,数量大小为 10,并意识到我想让程序更具动态性,因为我可能需要在某个给定点存储超过 10 个项目。我很难理解如何重新分配额外的内存,以便我可以存储我需要的任何数量的项目。这是处理此任务的正确方法吗?
主要功能:
double *purchases = (double*)malloc(QUANTITY_SIZE);
外功能
double startShopping(double *purchases, double *taxAmount, double *subTotal, double *totalPrice)
{
double itemPrice = 0.00;
double* storeMoreItems;
for(int i = 0; i < QUANTITY_SIZE; *subTotal +=purchases[i++])
{
while(itemPrice != -1)
{
printf("Enter the price of the item :");
scanf("%lf", &itemPrice);
storeMoreItems = (double*)realloc(storeMoreItems, i * sizeof(int));
if(storeMoreItems != NULL)
{
storeMoreItems = purchases;
purchases[i-1] = itemPrice;
}
else
{
free(purchases);
}
}
}
displayCart(purchases);
*taxAmount = *subTotal * TAX_AMOUNT;
*totalPrice = *taxAmount + *subTotal;
printf("\nTotal comes to : $%.2lf\n", *totalPrice);
return *totalPrice;
}