简体   繁体   中英

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

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);

} 

可以使用strdup代替malloc()来自动为您分配合适大小的缓冲区。

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM