今天给嵌套结构体赋值的时候编译没问题,但是运行总是段错误,后来发现是忘了分配动态内存,记得用calloc分配,实际结构体嵌套比较复杂,在这里举个简单的例子给大家看看,引以为戒。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
typedef int MsgCountltev_t;
typedef int MinuteOfTheYearltev_t;
typedef struct function
{
MsgCountltev_t msgCnt;
MinuteOfTheYearltev_t *timeStamp;
}SPAT_t;
int main()
{
SPAT_t *spat;
spat = calloc(1, sizeof(SPAT_t)); //一定要记得分配动态内存,不然直接段错误
spat->msgCnt = 10000;
printf("%d\n", spat->msgCnt);
spat->timeStamp = calloc(1, sizeof(MinuteOfTheYearltev_t)); //分配内存
*spat->timeStamp = 12345;
printf("%d\n", *spat->timeStamp);
return 0;
}
另外附上,calloc和malloc的区别:calloc在动态分配完内存后,自动初始化该内存空间为零,malloc不初始化,里边数据是随机的垃圾数据。