I want to calculate the length of an (at first) uninitialized char array.
My code is:
#include <stdio.h>
int main()
{
char *string_t;
int loc = sizeof(string_t)/sizeof(*string_t);
printf("%d", loc);
}
I expect loc to be 0 but instead loc is 8. Can someone tell me why this is and how I can "fix" this to be the answer I expect?
sizeof is a compile time operator (with the exception of VLA). The value of sizeof(string_t)/sizeof(*string_t) is equivalent to sizeof(char *) / sizeof(char), which is the size of a pointer, usually 8 on 64-bit machines.
For uninitialized char * pointer, there is no correct size, you have to initialize it:
char *string_t = "";
and use strlen(string_t) to get 0. However, since it's a pointer to a string literal, it's somehow pointless though.
you don't have a char array, you have a char *. To get what you want you need to something like :-
#include <stdio.h>
int main()
{
char string[100];
string[0]=0;
int loc = strlen(string);
printf("%d", loc);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With