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()
)