Using malloc to allocate memory for a string (c++

2019-09-02 10:47发布

问题:

I'm trying to create an array of a struct, which I have done and I have to receive an input from the user. The first piece of data would be the description (a string). I have to allocate memory for it as well. I'm not how big the string is going to be to I want to check as it's going in, but I don't think I've set it up right. Can anyone give me a hint or a page I can look at to figure it out?

Greatly appreciated. Here are the important snipits of code:

struct myExpenses
{
    char *description;
    float cost;
};


int main (void)
{


struct myExpenses *pData = NULL;
struct myExpenses expenses[60];
int exit=0;
int i = 0;
char buffer[81] = "";


printf("Please enter all your descriptions:\n");
for (i=0;i < 60; i++)
{
    fgets(buffer,stdin);
    expenses[i].description=(char *)malloc sizeof(buffer);

} 

回答1:

Instead of using malloc() you could use strdup that would automatically allocate the right sized buffer for you.

expenses[i].description = strdup( buffer );


回答2:

Besides you missing a pair of parentheses around the malloc call and not really telling what the problem is, you just allocate the memory but do not copy the string. It can be done in one function call instead with the strdup function:

printf("Please enter all your descriptions:\n");
for (i=0;i < 60; i++)
{
    fgets(buffer,stdin);
    expenses[i].description=strdup(buffer);
}

Remember to call free on all the descriptions when you are done with them, or you will have a memory leak.

Edit How to use free on the given example:

for (i = 0; i < 60; i++)
    free(expenses[i].description);


标签: c windows malloc