inSynergy
inSynergy

Reputation: 77

in the below program why is sizeof returning twice the array size initialized and not just one more byte?

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

Answers (3)

inSynergy
inSynergy

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

Iharob Al Asimi
Iharob Al Asimi

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

haccks
haccks

Reputation: 106012

C11: 6.5.3.4:

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

Related Questions