Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating length of uninitialized char array

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?

like image 674
Tyler Kelly Avatar asked Oct 21 '25 22:10

Tyler Kelly


2 Answers

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.

like image 54
Yu Hao Avatar answered Oct 25 '25 18:10

Yu Hao


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

}
like image 32
Keith Nicholas Avatar answered Oct 25 '25 18:10

Keith Nicholas