首页 > 解决方案 > `table = malloc(sizeof *table * count)`的模式

问题描述

我创建了这样一个程序,它试图使用代码结构来减少维护工作table = malloc(sizeof *table * 3);

#include <stdio.h>

struct today {
    int date;
    char weekday;
};

int main(void)
{   
    struct today *table;

    table = malloc(sizeof *table * 3);

    for (i = 0; i < 3; i++)
    {
        table[0].date = 20181022;
        table[0].weekday = 'M';
    }
    printf("%d, %c", table[0].date, table[0].weekday);

    free(table);

    return 0;
}

它可以工作并打印:

In [25]: !./a.out                                                                                                 
20181022, M

尽管如此,编译器还是会提醒多行警告

In [27]: !cc draft.c                                                                                              
draft.c:12:13: warning: implicitly declaring library function 'malloc' with type 'void *(unsigned long)'
      [-Wimplicit-function-declaration]
    table = malloc(sizeof *table * 3);
            ^
draft.c:12:13: note: include the header <stdlib.h> or explicitly provide a declaration for 'malloc'
draft.c:14:10: error: use of undeclared identifier 'i'
    for (i = 0; i < 3; i++)
         ^
draft.c:14:17: error: use of undeclared identifier 'i'
    for (i = 0; i < 3; i++)
                ^
draft.c:14:24: error: use of undeclared identifier 'i'
    for (i = 0; i < 3; i++)
                       ^
draft.c:21:5: warning: implicit declaration of function 'free' is invalid in C99 [-Wimplicit-function-declaration]
    free(table);
    ^
2 warnings and 3 errors generated.

在“生成 2 个警告和 3 个错误”中,我可以忽略哪一个?

标签: c

解决方案


您需要包含 stdlib.h 和 delcare i 作为整数。

#include <stdio.h>
#include <stdlib.h>

struct today {
    int date;
    char weekday;
};

int main(void)
{   
    struct today *table;

    table = malloc(sizeof *table * 3);

    if(table == NULL)
    {
        //Memory allocation failed
        //TODO: Handle this somehow.
    }

    for (int i = 0; i < 3; i++)
    {
        table[0].date = 20181022;
        table[0].weekday = 'M';
    }
    printf("%d, %c", table[0].date, table[0].weekday);

    free(table);

    return 0;
}

推荐阅读