我写了这段代码 (*pdata)->pProd = (Product*)malloc(sizeof(Product)*size1);
当我在“ (*pdata)->pProd
”中输入详细信息时,编译器停止了。如何为“ Product* pProd
”分配内存并输入详细信息?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char name[30];
int amount;
int price;
}Product;
typedef struct
{
int id;
Product* pProd;
int numProd;
}Cart;
void InitCashReg(Cart** pdata) {
int size,size1,j=0,i;
int PriceAllProd=0;
printf("Enter number of client --> \n");
scanf("%d", &size);
printf("Enter number of product client bought --> \n");
scanf("%d", &size1);
*pdata = (Cart*)malloc(sizeof(Cart)*size);
if (*pdata == NULL)
{
printf("cannot allocate memory\n");
return -1;
}
(*pdata)->pProd = (Product*)malloc(sizeof(Product)*size1);
if ((**pdata).pProd == NULL)
{
printf("cannot allocate memory\n");
return -1;
}
…
其中一条评论说:
我需要
size1
为每个size
客户分配产品空间,然后为每个客户输入产品的详细信息。
第一件事:
一个函数应该做一项工作——你的(至少)做两项工作:获取大小,并为给定这些大小的数据分配空间(然后可能继续用更多的 I/O 操作填充空间)。
这意味着您的代码应至少拆分为两个函数,其中第二个函数变成类似bool InitCashReg(size_t n_client, size_t n_prod, Cart **pdata)
,返回成功/真或失败/假状态,并将您调用的size
和size1
作为参数而不是试图读取它们。我不会复制 I/O 代码;我将只专注于内存分配代码。
enum { CLIENT_DEFAULT_ID = -1 };
bool InitCashReg(size_t n_client, size_t n_prod, Cart **pdata)
{
Cart *cart = malloc(sizeof(*cart) * n_client);
if (cart == 0)
return false;
for (size_t i = 0; i < n_client; i++)
{
cart[i]->pProd = calloc(sizeof(*cart[i]->pProd), n_prod);
if (cart[i].pProd == 0)
{
// Release already allocated space
for (size_t j = 0; j < i; j++)
free(cart[j]->pProd);
free(cart);
return false;
}
cart[i].numProd = n_prod;
cart[i].id = CLIENT_DEFAULT_ID;
}
*pdata = cart;
return true;
}
此代码尚未编译,更不用说测试了。
我曾经calloc()
分配产品数组,以便数据全部归零;您可以malloc()
改用并将name
,amount
和price
变量设置为0
其他方式。请注意,这与本发明一起CLIENT_DEFAULT_ID
确保所有分配的内存都初始化为已知值。
(C++ 具有可用于确保正确初始化的构造函数。C 没有构造函数,因此您必须确保已正确初始化分配的数据。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句