使用malloc为字符串分配内存(C ++源) [英] Using malloc to allocate memory for a string (c++ source)

查看:321
本文介绍了使用malloc为字符串分配内存(C ++源)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个结构数组,我已经完成了这个工作,我必须接收用户的输入.第一条数据将是描述(字符串).我也必须为其分配内存.我不是想输入的字符串有多大,但我认为我没有正确设置它.谁能给我提示或我可以查看的页面以找出答案?

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()来自动为您分配合适大小的缓冲区.

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

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

这篇关于使用malloc为字符串分配内存(C ++源)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆