Question

I am trying to get the length of a string but i am getting the wrong value, it is saying that it is only 4 characters long. Why is this? am i using sizeof() correctly?

#include <stdio.h>

int main(void)
{
    char *s;
    int len;

    s = "hello world";
    len = sizeof(s);
    printf("%d\n", len);
}
Was it helpful?

Solution

The sizeof operator is returning the size of the pointer. If you want the length of a string, use the strlen function.

Even if you had an array (e.g. char s[] = "hello world") the sizeof operator would return the wrong value, as it would return the length of the array which includes the string terminator character.

Oh and as a side note, if you want a string pointer to point to literal string, you should declare it const char *, as string literals are constant and can't be modified.

OTHER TIPS

You have declared s as a pointer. When applied to a pointer, sizeof() returns the size of the pointer, not the size of the element pointed to. On your system, the size of a pointer to char happens to be four bytes. So you will see 4 as your output.

In addition to strlen(), you can assign string literal to array of chars char s[] = "hello world", in this case sizeof() returns size of array in bytes. In this particular case 12, one extra byte for \0 character at the end of the string.

Runtime complexity of sizeof() is O(1).

Complexity of strlen() is O(n).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top