Matthias Burger Matthias Burger - 4 years ago 85
C Question

chararray size and length are not the same

I just started learning C after I already got a few years experience in Python, C# and Java.

I learned in a tutorial, that

char anything[]
is always a pointer. (Today, someone told me this is wrong) - I think my question has something to do with this.
Nevertheless, I'm trying to get the length of a char-array:

#include <stdio.h>

int get_string_length(char * string)
{
int length = 0;
while(string[length] != '\0')
{
char c = string[length];
length++;
}
return length;
}

int get_string_size(char * string)
{
return sizeof(string);
}

int main()
{
printf("%d\n", get_string_size("hello world")); // returns 8
printf("%d\n", get_string_length("hello world")); // returns 11
printf("%d\n", sizeof("hello world")); // returns 12 -> Okay, because of '\0'-char
return 0;
}


result:


8

11

12


so, why is my
get_string_size
-method returning 8 instead of 12? (Since both only call
sizeof()
)

Answer Source

char anything[] is a pointer? Not quite.

The actual type of the literal "hello world" is a const char[12]. (Note the extra element for the NUL-terminator).

But when passed to a function, this type decays to a const char*.

So get_string_size returns sizeof(const char*) which is 8 on your platform (i.e. the sizeof a char*), but sizeof("hello world") is sizeof(const char[12]) which is 12, since sizeof (char) is defined by the C standard to be 1.

get_string_length is returning the position of the first NUL terminator starting from the pointer passed to it.

Finally, note that you should use %zu as the format specifier for the sizeof return type: technically the behaviour of printf("%d\n", sizeof("hello world")); is undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download