在C中创建新结构时如何正确分配足够的内存(malloc)?

问题描述 投票:-1回答:1

鉴于下面的结构,我正在创建一个函数,该函数接受person_in_queueposition_num并分配一个新的queue_t结构,该结构将添加到queue_t结构列表的末尾,如第一个论点。

typedef struct queue {
  int position_num;
  char *person_in_queue;

  struct queue *next_in_line;
} queue_t;

我已经这样写了代码:

queue_t *add_to_queue(queue_t *input_queue, char *person_in_queue, int position_num) {

  input_queue = malloc(sizeof(queue_t));
  assert(input_queue != NULL);

  input_queue->position_num = position_num;
  input_queue->person_in_queue = (char *) malloc((strlen(new_text) + 1) * sizeof(char));
  assert(input_queue->person_in_queue != NULL);

  strcpy(input_queue->person_in_queue, person_in_queue);
  return input_queue;

}

但是上述代码已编译,但由于分配的内存少于预期的内存,因此我被告知代码失败。目前,我不确定在这里哪里出错了。请注意,我需要使用malloc()

非常感谢!

c struct malloc typedef deep-copy
1个回答
0
投票
要为结构分配内存,请使用类型的大小。
© www.soinside.com 2019 - 2024. All rights reserved.