查找链接列表

时间:2016-08-11 04:19:48

标签: c list hyperlink

我正在浏览链表。我只想查找链表的每个节点的strlen

这是节点:

    struct node  
    {
       long HuffmanCodes;
       struct node *next;
    };
    struct node *head = NULL;
    struct node *current = NULL;

现在遍历并查找链接列表的每个节点的strlen

 int HuffmanCodeslength = 0;
 struct node *ptr = head;
 while(ptr != NULL)
 {
     HuffmanCodeslength = strlen(ptr->HuffmanCodes);
     ptr = ptr->next;   
 }
 ptr = head;
  

我不知道

strlen(ptr->HuffmanCodes)
  

是否有可能。   当我运行此代码时。它在运行时停止工作。   错误在哪里?

2 个答案:

答案 0 :(得分:0)

让我们暂时考虑一下。当strlen(ptr->HuffmanCodes)给出int整数时,您询问是否可以执行ptr->HuffmanCodes并将该值分配给long。为什么不试试这个(并注意警告)?

假设我们有简单的程序:

#include <stdio.h>
#include <string.h>

int main(void) {
  long myLongInt = 4873874;
  printf("%zd\n", strlen(myLongInt));
  return 0;
}

基本上,你试图找到long的字符串长度(而strlen通常用于字符串)。

以下是我们尝试编译时会发生的事情:

user@user Stack Overflow $ gcc dynamic_testing.c
dynamic_testing.c:6:26: warning: incompatible integer to pointer conversion passing 'long' to parameter of type 'const char *'
      [-Wint-conversion]
  printf("%zd\n", strlen(myLongInt));
                         ^~~~~~~~~
/usr/include/string.h:82:28: note: passing argument to parameter here
size_t   strlen(const char *);
                            ^
1 warning generated.

显然,由于strlen期望const char *并且我们传递long,因此存在不匹配。你不能做这个。此外,输出:

user@user Stack Overflow $ ./a.out
Segmentation fault: 11
user@user Stack Overflow $

然后,当您首先导致分段错误时,尝试将此值分配给int

很简单:strlen(ptr->HuffmanCodes)不是法律声明。我不明白你为什么试图获得long int的字符串长度。

答案 1 :(得分:0)

strlen()仅用于字符串/字符数组。

如果你想找出每个节点的长度,你需要使用sizeof(struct node);

或找到sizeof HuffmanCodes使用sizeof(ptr->HuffmanCodes);