我试图将存储分配给结构指针。这是删节的代码——你能告诉我我做错了什么吗?
can.h
#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\c 20 2 Can5
在"packet_Tx"c:\users\blu\documents\avrstudio\Can5\Can5\c 20 2 Can5 的声明中,警告2类型默认为"int"
"packet_Tx"c:\users\blu\documents\avrstudio\Can5\Can5\c 20 2 Can5 的错误3类型冲突
错误4"packet_Tx"的先前声明位于c:\users\blu\documents\avrstudio\Can5\Can5\c 18 13 Can5
警告5初始化使指针中的整数不带强制转换c:\users\blu\documents\avrstudio\Can5\Can5\c 20 14 Can5
当packet_Tx赋值行被注释掉时,代码的其余部分就可以很好地执行了。非常感谢各位。
在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;