Mohit Mohit - 1 year ago 50
C Question

Finding String Length of one node of linked list

I am traversing linked list. I just want to find

of each node of linked list.

Here is node:

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

Now Traversing and finding
of each node of linked list.

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

I don't know


is possible or not.
When I run this code. It stopped working on runtime.
Where is the mistake?

Answer Source

Let's just think about this for a second. You are asking whether doing strlen(ptr->HuffmanCodes) and assigning that value to an int is possible, when ptr->HuffmanCodes gives a long integer. Why not just test this out (and pay attention to the warnings)?

Say we have the simple program:

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

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

Since basically, you are trying to find the string length of a long (and strlen is normally used with strings).

Here is what happens when we try to compile this:

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 *'
  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.

Clearly, there is a mismatch since strlen expects a const char * and we are passing a long. You cannot do this. Furthermore, the output:

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

Then you try to assign this value to an int when in the first place it causes a segmentation fault.

Quite simply: strlen(ptr->HuffmanCodes) is not a legal statement. I don't understand why you are trying to get the string length of a long int.