Why is sizeof(a) zero? where a is int a[0]?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kakultech
    New Member
    • Jan 2013
    • 2

    Why is sizeof(a) zero? where a is int a[0]?

    $ cat VLA.c

    Code:
    #include<stdio.h>
    void main()
    {
            int a[0];
            int *b;
    
            /*As we say a[0] is equivalent to *(a+0) */
            printf("\n a = %d b = %d",sizeof(a),sizeof(b));
    }
    
    $gcc VLA.c
    $ ./a.out
    
     a = 0 b = 4
    Why sizeof(a) is zero ?
    Last edited by Meetee; Jan 21 '13, 11:09 AM. Reason: Use code tags <code/> around code
  • Gobi Sakthivel
    New Member
    • Jan 2013
    • 26

    #2
    u have declared int a[0], which means declaring an array which contains no elements, tats y it is returning as 0.Also u cant do anything with it, it is of no use, to declare an array with 0 elements.

    Comment

    • kakultech
      New Member
      • Jan 2013
      • 2

      #3
      Thanks for reply.
      How should we differentiate int a[0] and int *b ? As we say a[0] is equivalent to *(a+0), which is nothing but *a.

      Comment

      • Gobi Sakthivel
        New Member
        • Jan 2013
        • 26

        #4
        int *b, is a pointer to an integer and int a[n], is an array of n integers. Dont get confused by the two.


        if we declare int *b; 4 bytes of memory will be allocated
        for it (considering sizeof int as 4).

        consider b points to memory location 1000 , so b[0]==*(b+0) points to 1000,
        b[1]==*(b+1) points to 1004
        and so on.

        if we declare int a[0];
        intially no memory gets allocated for it.
        but when do some operations like a[0]=2; then 'a' will points to some memory location say '2000'
        no a[1] will points 2004 and goes on.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          By the way, line 2 should be
          Code:
          int main(void)
          As a consequence of making this change, you will need to return a value from main.

          Comment

          • swapnali143
            New Member
            • Mar 2012
            • 34

            #6
            for any pointer size is 4 Bytes because.. Pointer is used to store memory address and every memory address in Computer are integer valuse so sizeof((int*a)) is always 4 bytes...

            Comment

            Working...