将malloc与结构

时间:2017-03-19 23:06:59

标签: c struct malloc

正在阅读这里的一些主题并观看一些YouTube视频,并努力让malloc“点击”我正在尝试做的任务。

如果这是重复的话,请提前道歉但我在另一个帖子上找不到明确的答案。

假设我有一个结构用于定义声明如下的个人数据:

    struct strDate
    {
        int     nDay;
        int     nMonth;
        int     nYear;
    };

    struct  strTime
    {
        int     nSeconds;
        int     nMinutes;
        int     nHours;
    };

    struct strName
    {
        char            arcTitle[10];
        char            arcFirstName[50];
        char            arcMiddleName[50];
        char            arcSurname[50];
    };

    struct strPerson
    {
        struct strDate  strDOB;
        struct strName  strFullName;
        struct strTime  strStartTime;
        struct strDate  strStartDate;
        char            arcJobTitle[31];
        int             nEmployeeNumber;
    };

我目前对Malloc的理解如下:

Malloc可用于确定存储值所需的内存量(取决于类型和大小等)。这可以应用于创建链接列表,方法是将指针放在每个值的末尾,指向列表中的下一个值。

我如何将malloc应用于我的代码?

如果我有一个结构数组,如下所示:

    // Variable Declarations
    struct strPerson    Person[5];

假设我想首先用空白占位符填充数据(以防止从内存中提取垃圾值),然后用数据填充结构,我如何确保它使用malloc的适当内存量? / p>

我目前正在这样做而没有malloc,但我认为这是低效的,因为它可能超过一个字符串数组长度。无论如何:

// Blank Data
for (nCount = 0; nCount < 5; nCount++)
        fnDefaultBlankPersonData(&Person[nCount]); // fills all structures with blank data to avoid unusual values pulled from memory


// Real Data
fnPopulatePersonData(&Person[0], "Mr", "PlaceholderFirst", "PlaceholderMiddle", "PlaceholderLast", "PlaceholderJobTitle", 1, 1, 1980, 1, 9, 2001, 8, 0, 0, 6);

主要关注上面的“真实数据”群体:如何确保结构大小适合数据,如果我重新运行函数以重新填充它,可以调整大小?

(上面的两个函数只是使用=和strcpy())

为结构赋值

1 个答案:

答案 0 :(得分:4)

malloc函数用于确定存储值所需的内存量。 sizeof运算符执行此操作。

malloc所做的是为程序的使用动态分配给定数量的内存。

在您的用例中,看起来您不需要malloc。您正在寻找清除内存的一部分,以便它包含已知值。如果您希望所有字节都包含0,则可以使用memset函数:

for (nCount = 0; nCount < 5; nCount++)
    memset(&Person[nCount], 0, sizeof(Person[nCount]);

更好的是,您可以一次为整个数组执行此操作,而不是每个元素执行一次:

memset(Person, 0, sizeof(Person);