Thread: Sizeof used to gauge no. of elements of array passed to function - dubious behaviour

  1. #1
    Registered User
    Join Date
    Jun 2015
    Location
    Delhi
    Posts
    35

    Sizeof used to gauge no. of elements of array passed to function - dubious behaviour

    In this program, on using sizeof to compute no. of elements in array x, it works fine:

    Code:
    #include<stdio.h>
    int main()
            {
                    int x[5]={23,54,3,5,6};
                    int k=(sizeof(x)/sizeof(x[0]));
                    printf("%d\n",k);
                    return 0;
            }
    But, when I pass it as a parameter to a function, it gives incorrect result:

    Code:
    #include<stdio.h>
    void fun(int x[])
            {
                   int k=(sizeof(x)/sizeof(x[0]));               
                   printf("%d\n",k);
            }
    int main()
            {
                    int x[5]={23,54,3,5,6};
                    fun(x);
                    return 0;
            }
    It is also giving two different result on ideone and my system.
    Why this is happening?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Why this is happening?
    When you passed the array into the function you passed a pointer to the first element of the array, not the actual array. Because of this you when you use the sizeof operator it will report the sizeof the pointer, not the sizeof the array. If you need to know the sizeof the array in the function you'll need to pass this information into the function as a parameter.

    It is also giving two different result on ideone and my system.
    There is probably a difference in the sizes of the pointers in the two compilers. One of the compilers is probably a 32 bit compiler and the other is probably a 64 bit compiler.

    Jim

  3. #3
    Registered User
    Join Date
    Jun 2015
    Location
    Delhi
    Posts
    35
    Thanks for pointing me into right direction.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-13-2012, 09:19 AM
  2. Strange sizeof() behaviour
    By Phenom in forum C++ Programming
    Replies: 6
    Last Post: 02-09-2011, 02:40 AM
  3. Dynamic Array Passed to a function by Reference
    By patriots21 in forum C Programming
    Replies: 7
    Last Post: 11-21-2010, 11:32 AM
  4. dubious sizeof operator
    By lazy_hack in forum C Programming
    Replies: 5
    Last Post: 08-23-2009, 08:44 AM
  5. sizeof behaviour!!
    By lawina in forum C Programming
    Replies: 3
    Last Post: 12-27-2006, 11:47 AM