Chararray size and length do not match

I just started learning C after I already have several years of experience in Python, C #, and Java.

In the tutorial, I found out that char anything[] always a pointer. (Today someone told me that this is wrong). I think my question has something to do with it. However, I am 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:

-

eleven

12

So why is my get_string_size method returning 8 instead of 12? (Since both calls are only sizeof() )

0
c arrays
Feb 06 '17 at 1:31 on
source share
3 answers

char anything[] is a pointer? Not really.

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

But when it is passed to the function, this type decays to const char* .

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

get_string_length returns the position of the first NUL terminator, starting with the pointer passed to it.

Finally, note that you should use %zu as the format specifier for the returned sizeof : technically, the behavior printf("%d\n", sizeof("hello world")); equals undefined.

+5
Feb 06 '17 at 13:34 on
source share

Always use the strlen () parameter to determine the length of the string.

Using sizeof () for string length is dangerous and should be avoided. sizeof () returns the size of this type, in which case this type is a pointer (your system should be 64-bit, since the size is 8).

Consider this code and its output:

 char string[] = "This is a test"; char *pointer = string; printf("sizeof string: %zu\n", sizeof(string)); printf("sizeof pointer: %zu\n", sizeof(pointer)); printf("strlen pointer: %zu\n", strlen(pointer)); sizeof string: 15 sizeof pointer: 8 strlen pointer: 14 
+2
Feb 06 '17 at 13:34 on
source share

It does not do what you think:

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

Here sizeof(string) is the size of the pointer, which is always 8 on your (presumably 64-bit) platform. On a 32-bit platform, this would most likely be 4 instead of 8.

On the other hand, sizeof("hello world") is the memory size taken by the string literal "hello world" , which is 11 + 1 (+1 for the NUL terminator).

+1
Feb 06 '17 at 13:33
source share



All Articles