Reputation: 77
My prgram has no errors I just need an explanation on how the sizeof
part works here
#include <stdio.h>
int main(int argc, char const *argv[])
{
char food[5];
printf("Enter your favorite food:\n");
//here sizeof doubles array size why??
fgets(food, sizeof(food+1), stdin);
printf("Great choice I love %s\n", food);
return 0;
}
Upvotes: 0
Views: 106
Reputation: 77
It seems I was reading and found that sizeof(variable)
returns the size of the variable, so when I declared sizeof(food)
the food
variable takes the size of the character array and then adding one means, the compiler actually doubles the size of the variable by adding one more array of the same size, i.e. allocates space in memory.
sizeof(food + 1)
Allocates space that is double the size of food
.
sizeof(food)+1
Allocates space that is 1-byte more than food
.
BTW I'm using gcc compiler in Ububtu 14.04
Thank You Guys for helping.
Upvotes: 1
Reputation: 53006
It does not double the array size, it gives the size of a pointer. When doing pointer arithmetics with the array sizeof
considers the argument as a pointer, and gives the size of the argument's type, instead of the size of the array.
And since the argument is a pointer, the value is equivalent to sizeof(void *)
.
Upvotes: 1
Reputation: 106012
The
sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.
The type of expression food + 1
is of pointer to char
. Therefore sizeof(food+1)
will return the size of pointer.
Upvotes: 4