Making my own strlen function with receiving string as linked list

144 views Asked by At

I was having practice using linked list and was trying to make my own strlen function in string header. First, I made my own header like this.

myHeader.h

typedef struct _str {
    char c;
    struct _str *l;
}
typedef cp2014str *cp2014strPtr;
size_t cp2014strlen(const cp2014str * str);

size_t cp2014strlen(const cp2014str * str) {
    size_t i;
    cp2014strPtr strptr;
    strptr = str;
    for(i = 0; strptr != NULL; i++) {
        strptr = strptr -> l;
    }
    return i - 1;
}

and I tested my own strlen with this code

 #include <string.h>
 #include "myHeader.h"
 int main() {
     int i, j;
     i = strlen("Happy");
     j = cp2014strlen("Happy");
     printf("%d %d\n", i, j);
     return 0;
 }

but after I compiled and run, even though there was no compile error, segmentation fault occurred in the process of running program. I couldn't figure out why it is wrong.

1

There are 1 answers

0
JS1 On BEST ANSWER

"Happy" is a string, not a linked list. To use your function, you need to make a linked list with each letter as a node in the list.