我试图将存储分配给结构指针。这是删节的代码-你能告诉我我做错了什么吗?
罐头
#ifndef CAN_H_
#define CAN_H_
typedef struct {
u32 id;
u32 mask;
char length;
char data[8];
char status;
} CAN_PACKET;
项目c
#include "can.h"
CAN_PACKET *packet_Tx, *packet_Rx;
CAN_PACKET packet1, packet2;
packet_Tx = (CAN_PACKET*)malloc(sizeof(CAN_PACKET)); /* line 20 in text */
packet_Tx = &packet1; packet_Rx = &packet2;
int main(void)
{
while(1)
{
}
}
我收到这些错误/警告:
警告1数据定义没有类型或存储类c:\users\blu\documents\avrstudio\Can5\Can5\Can5.c 20 2 Can5
警告2“packet-Tx”声明中的类型默认为“int”c:\users\blu\documents\avrstudio\Can5\Can5\Can5.c 20 2 Can5
错误3“packet\u Tx”的冲突类型c:\users\blu\documents\avrstudio\Can5\Can5.c 20 2 Can5
错误4“packet-Tx”的前一个声明位于此处c:\users\blu\documents\avrstudio\Can5\Can5\Can5.c 18 13 Can5
警告5初始化使指针中的整数不带强制转换c:\ users\blu\documents\avrstudio\Can5\Can5\Can5.c 20 14 Can5
当数据包分配行被注释掉时,代码的其余部分就可以正常工作了谢谢你们。
最佳答案
在C语言中,不能有函数外的代码移动这两行:
packet_Tx = (CAN_PACKET*)malloc(sizeof(CAN_PACKET));
packet_Tx = &packet1; packet_Rx = &packet2;
到
main()
方法的顶部:int main(void)
{
packet_Tx = (CAN_PACKET*)malloc(sizeof(CAN_PACKET));
packet_Tx = &packet1; packet_Rx = &packet2;