Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof of string literal inside a struct - C

Tags:

c

I have the following code:

struct stest
{
    int x;
    unsigned char data[];
} x = 
{
    1, {"\x10\x20\x30\x00\x10"} 
};

int main()
{
    printf( "x.data: %d\n", (int)x.data[0] );
    return 0;
}

Which works fine. However, I need to use the size of the "data".

If I do:

printf( "sizeof x.data: %d\n", (int)sizeof(x.data) );

I get the error:

invalid application of ‘sizeof’ to incomplete type ‘char[]’

Is there a way to get the size of "data" in this situation, or maybe a suggestion of an alternative method I could use?

The compiler I am using is gcc 4.6.3.

like image 892
Renan Greinert Avatar asked Nov 28 '25 01:11

Renan Greinert


1 Answers

Since x.data is a null terminated char array you could just use strlen function.

printf( "sizeof x.data: %u\n", strlen(x.data)+1 );

This code will not work correctly if the array contains null. In this case you need to store length of the array in separate member of struct.

like image 92
kvorobiev Avatar answered Nov 30 '25 16:11

kvorobiev