sizeof() function in C

72,402

Solution 1

Whenever you refer to the name of the array in your program, It normally decays to a pointer to the first element of the array. One of the exception to this rule is the sizeof operator. So when you consider the following code.

int main()
{
   char a[] = "Visual C++";
   printf("sizeof(a)=%d\n",sizeof(a)); /* Here sizeof(a) indicates sizeof array */
   printf("a=%p",a); /* Here the array name, passed as an argument to printf decays into a pointer of type (char *) */
   return 0;
}

Solution 2

In the declaration char a[] = "Visual C++", a is an array of 11 char. So its size is 11 bytes.

In the declaration char *b = "Visual C++", b is a pointer to char. So its size is four bytes (in the C implementation you are using).

In the expression printf("%s", a), a is also an array. However, it is automatically converted to a pointer to the first element of the array. So a pointer to char is passed to printf.

This conversion happens automatically unless an array is the argument of &, sizeof, or _Alignof or is a string literal used to initialize an array of char. Because it happens automatically, people tend to think of array names as pointers. However, they are not.

Incidentally, sizeof is an operator, not a function.

Solution 3

When sizeof is applied to the name of a static array (not an array allocated through malloc), the result is the size in bytes of the whole array. This is one of the few exceptions to the rule that the name of an array is converted to a pointer to the first element of the array, and is possible just because the actual array size is fixed and known at compile time, when sizeof operator is evaluated.

Share:
72,402
Shivaji_Vidhale
Author by

Shivaji_Vidhale

Updated on January 03, 2020

Comments

  • Shivaji_Vidhale
    Shivaji_Vidhale over 4 years
    main()
    {
    char a[] = "Visual C++";
    char *b = "Visual C++";
    printf("\n %d %d",sizeof(a),sizeof(b));
    printf("\n %d %d",sizeof(*a),sizeof(*b));
    }
    

    sizeof(a) gives me output: 11 ( that is length of the string)

    Why is it so ?
    Why isn't the output sizeof(a)=4 since when I try to print a it gives me an address value and hence an integer?