-1

可能重复:
对数组使用动态内存分配

我最初有这个程序商店的价格,数量大小为 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;
}
4

4 回答 4

1

double* purchases = (double*)malloc(sizeof(double)*QUANTITY_SIZE);

更:

storeMoreItems = (double*)realloc(storeMoreItems, i * sizeof(double));

您尝试分配i*sizeof(int),然后将其转换为double*. 当您的代码具有不同的大小时,将很难找到错误doubleint

接下来的事情:

i等于 0 时,您分配初始大小为 0 字节 ( i*sizeof(int)) 的内存,然后尝试使用它。它行不通。尝试以这种方式更改循环:for (int i = 1, i <= QUANTITY_SIZE;...并保持purchases[i-1].

于 2012-12-27T19:23:05.950 回答
1

这是错误的:

        if(storeMoreItems != NULL)
        {
            storeMoreItems = purchases;
            purchases[i-1] = itemPrice;
        }

首先,你覆盖刚刚的realloced 指针,你的意思是

purchases = storeMoreItems;

那里而不是相反。但这不会影响传入的purchases指针在调用函数中的值。

为此,您需要将purchasesfrom的地址传递main

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;
}
于 2012-12-27T19:27:47.167 回答
0

您要做的第一件事是确保分配正确的字节数。Malloc 不知道您想将内存用于双打,因此您需要乘以sizeof(double)

double *purchases = (double*)malloc(QUANTITY_SIZE * sizeof(double));
于 2012-12-27T19:22:30.490 回答
0

查看重新分配。

void * realloc ( void * ptr, size_t size );

重新分配内存块 更改 ptr 指向的内存块的大小。

从这里获取更多详细信息http://www.cplusplus.com/reference/cstdlib/realloc/

于 2012-12-27T19:24:08.390 回答