无法初始化结构链表

时间:2014-05-15 09:51:46

标签: c

无法初始化结构链表 每次我将var设置为ftt.foods-> head->数据时,我都会遇到分段错误(核心转储),我不知道它为什么会出现段错误。如果我在BOOLEAN init(ftt_type * ftt)中的malloc ftt类型ftt将无法获取内存,大家可以告诉我我的程序有什么问题吗? 如果我需要在init()函数中使用malloc(),那该怎么办?

结构食物     {         char id [IDLEN + 1];         char name [FOODNAMELEN + 1];         char desc [DESCLEN + 1];         结构货币价格;     };

struct ftt_node
{
    struct food * data;
    struct ftt_node * next;
};

struct ftt_list
{
    struct ftt_node * head;
    unsigned list_len;
};


/* data definitions for the coins array */

enum denomination
{
    FIVE_C,TEN_C,TWENTY_C,FIFTY_C,
    ONE_D,TWO_D,FIVE_D,TEN_D,TWENTY_D,FIFTY_D
};

struct coin
{
    enum denomination denom;
    unsigned count;
};

#define NUMDENOMS 10

/* header containing list and coins */

typedef struct ftt
{
    struct ftt_list * foods;
    struct coin coins[NUMDENOMS];
} ftt_type;



init fuction
        BOOLEAN init(ftt_type * ftt)
    {   
        printf("init_ftt values:%d",ftt);   
        memset(ftt->coins,0,(size_t)NUMDENOMS * sizeof(struct coin));
        printf("\n\n\n\nmemset count check:%d\n",ftt->coins->count);
        printf("\nmemset denom check:%d\n",ftt->coins->denom);
        /*memset(ftt->foods->listlen,0,IDLEN + 1);*/ 
        ftt->coins->count=0; 
        ftt->foods->list_len=0;
        memset(ftt->foods,0,sizeof(struct ftt_list));
        ftt->foods->head->data->price.dollars=100;
        ftt->foods->head->data->price.cents=100;



        printf("**************************************************can not set variable to ftt->foods->head->data->name*******************************\n\n");        strcpy(ftt->foods->head->data->id,"good");
        strcpy(ftt->foods->head->data->name,"good");
        strcpy(ftt->foods->head->data->desc,"good");
        ftt->foods->head->data->price.dollars=100;
        ftt->foods->head->data->price.cents=100;
        printf("\nmemset desc check:%s\n",ftt->foods->head->data->desc);

        return TRUE;
    }

 int main(int argc, char **argv)
{
    ftt.foods = (struct ftt_list *) malloc(sizeof(struct ftt_list)); 
    ftt.foods->head = (struct ftt_node *)malloc(sizeof(struct ftt_node));  
    ftt.foods->head->data=(struct food *)malloc(sizeof(struct food));
    ftt_type  ftt;

    init(&ftt);
    return EXIT_SUCCESS;
    }

1 个答案:

答案 0 :(得分:2)

init()函数中,您正在执行

memset(ftt->foods,0,sizeof(struct ftt_list));

这将覆盖ftt->foods的成员,因此您将丢失分配给ftt->foods->head的内存。

因此,当您尝试访问ftt->foods->head->data时,您正在访问空指针ftt->foods->head

您应memset()之前malloc()或更确切地使用calloc()