c - `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 个错误”中,我可以忽略哪一个?
解决方案
您需要包含 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;
}
推荐阅读
- django - 数组不要在模板中访问
- oauth-2.0 - 如何使用 Cloud Foundry api 获取令牌?
- json - 如何在 swago 文档中省略某些字段
- ios - 使用 Alamofire 在苹果商店中发布
- angular - 如何dockerize dotnet core angular模板应用程序?
- java - java中的reverseOrder排序
- c++ - 最大升序连续子数组的递归长度(C++)
- database-design - 为客户和客户在其上具有主地址的地址设计表的更好方法是什么?
- tesseract - pytesseract 不使用用户词
- html - 如何删除我的联系表格中多余的填充?