How to find the length of a char array


int func(char S[]){
     // write code
}

I got a question like this on gfg. I wanted to use the length of the char array in my function but can’t find a way to determine it.

I used

int n = sizeof(S);

but this doesn’t seems to work.

when you pass char S[] as a parameter, you’re passing a pointer, and the size of a pointer is 4 bytes so sizeof() doesn’t work. You can try using strlen() function but it will only work if ur array is null terminated and will take time O(n).
So you either need to pass the length along with the array, use something STL provides like std::array, or make ur char array null terminated and use strlen().

3 Likes

Yeah but on a coding platform (like gfg) its not possible to redefine the provided function. And it was a c program actually.

1 Like

strlen() will work in most of the cases, unless the character array ends with a null character ('\0'). You might want to explore the calling function to manipulate the code.

Yeah it worked thanks

a neat way to do that is -

int n = sizeof(S)/sizeof(char);

This will not work when passed to a function.

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

void fun(char s[]) {
    int length = sizeof(s) / sizeof(char);
    printf("Length = %d\n", length);
}

int main() {
    char s[] = "Hello, World!";
    fun(s);
    return 0;
}
main.c:7:24: warning: ‘sizeof’ on array function parameter ‘s’ will return size of ‘char *’ [-Wsizeof-array-argument]                           
     int length = sizeof(s) / sizeof(char);                                                                                                     
                        ^                                                                                                                       
main.c:6:15: note: declared here                                                                                                                
 void fun(char s[]) {                                                                                                                           
               ^                                                                                                                                
Length = 8
1 Like