Search code examples
cstringpointersstring-length

Coding a string length function using pointer arithmetic


I'm in a beginner CS class learning C and we were tasked with coding a function to find string length using only string pointers. I have the following code:

#include <stdio.h>

int strlength(char* str);

int main() {
    char *str;
    int comp;

    printf("Please enter the string: ");
    scanf("%s", str);

    printf("The length of the string is: %d\n", strlength(str));
    return 0;
}

int strlength(char *str) {
    int length = 0;

    while(*str != '\0') {
        length++;
        str++;
    }
    return length;
}

I'm not really sure where I'm getting a segmentation fault. I've tried making a second pointer in the strlength function that equals str and incrementing that, but that also gives me a segmentation fault. Any insight would be appreciated!


Solution

  • char *str;
    int comp;
    
    printf("Please enter the string: ");
    scanf("%s", str);
    

    You should allocate memory in heap ( with malloc ) for *str before scanf. If you dont want to use malloc change it to char[number] so it can allocate memory in stack instead of heap