【问题标题】:C linked list: head is changingC链表:头在变化
【发布时间】:2013-09-09 06:13:17
【问题描述】:

我正在使用结构作为链接列表,但由于最近发生了变化(我忘记检查 git 存储库,所以我不记得 哪个 更改了)我的结构变量之一头部元素正在改变。 在执行下面显示的代码时,post->filename 得到了一个有效的字符串,但在离开方法后,head_post->filename(应该指向完全相同的值)添加了一些垃圾。字符串“20130804-0638.md”变为“20130804-0638.md�:\020”。

知道我想念什么吗?

结构:

struct posting {
    char *filename;
    char  timestamp[17];
    char *url;
    char *title;
    char *html;
    struct posting *next;
};
struct posting *head_post = NULL;

代码:

struct posting *post;
...
while ((ep = readdir(dp))) {
  if (ep->d_name[0] != '.' && strstr(ep->d_name, ".md") && strlen(ep->d_name) == 16) {
    if (head_post == NULL) {
      head_post = malloc(sizeof(struct posting));
      post = head_post;
    } else {
      post = head_post;
      while (post->next != NULL)
        post = post->next;
      post->next = malloc(sizeof(struct posting));
      post = post->next;
    }

    post->filename = malloc(sizeof(char) * strlen(ep->d_name));
    strcpy(post->filename, ep->d_name);
    post->next = NULL;
  }
}

【问题讨论】:

  • 如果您从 repo 下载最后一个版本,您应该能够获取两个文件的差异,这将突出显示更改。 ...除非您在许多更改中忘记执行此操作。

标签: c list pointers struct linked-list


【解决方案1】:

我认为在为filename 分配内存时,您还需要计算'\0',因为strlen() 不计算在内。

... 
//                                           ------------- +1 for '\0'
post->filename = malloc(sizeof(char) * (strlen(ep->d_name) +1 ));
strcpy(post->filename, ep->d_name);
post->next = NULL;
...

【讨论】:

  • 我大部分时间都这样做了,现在我什至没有想到这一点。谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 2015-06-27
  • 1970-01-01
  • 2016-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多