【问题标题】:Cannot initialize a structure linked list无法初始化结构链表
【发布时间】:2014-07-03 16:44:33
【问题描述】:

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

结构食物 { 字符 ID[IDLEN + 1]; 字符名称[FOODNAMELEN + 1]; 字符描述[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;
    }

【问题讨论】:

  • 你不必在平面 C 中强制转换 malloc 的返回值,是吗?

标签: c


【解决方案1】:

init()函数中,你正在做

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

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

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

您应该在malloc() 之前使用memset(),或者使用calloc()

【讨论】:

  • 非常感谢它可以工作,但是如果我需要在 init() 中使用 malloc() 怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多