Reputation: 1670
Why is size of this char variable equal 1?
int main(){
char s1[] = "hello";
fprintf(stderr, "(*s1) : %i\n", sizeof(*s1) ) // prints out 1
}
Upvotes: 1
Views: 25027
Reputation: 1206
sizeof(*s1) means its denotes the size of data types which used. In C there are 1 byte used by character data type that means sizeof(*s1) it directly noticing to the character which consumed only 1 byte.
If there are any other data type used then the **sizeof(*data type)** will be changed according to type.
Upvotes: 1
Reputation: 133669
Because you are deferencing the pointer decayed from the array s1
so you obtain the value of the first pointed element, which is a char
and sizeof(char) == 1
.
Upvotes: 5
Reputation:
sizeof(*s1)
means "the size of the element pointed to by s1
". Now s1
is an array of char
s, and when treated as a pointer (it "decays into" a pointer), dereferencing it results in a value of type char
.
And, sizeof(char)
is always one. The C standard requires it to be so.
If you want the size of the whole array, use sizeof(s1)
instead.
Upvotes: 3
Reputation: 145919
NOTA: the original question has changed a little bit at first it was: why is the size of this char pointer 1
sizeof(*s1)
is the same as
sizeof(s1[0])
which is the size of a char
object and not the size of a char
pointer.
The size of an object of type char
is always 1
in C.
To get the size of the char
pointer use this expression: sizeof (&s1[0])
Upvotes: 14
Reputation: 206646
Why is size of this char variable equal 1?
Because size of a char
is guaranteed to be 1
byte by the C standard.
*s1 == *(s1+0) == s1[0] == char
If you want to get size of a character pointer, you need to pass a character pointer to sizeof
:
sizeof(&s1[0]);
Upvotes: 7