Thread: sizeof inside function

  1. #1
    Registered User
    Join Date
    Jul 2015
    Posts
    1

    sizeof inside function

    Hi everyone,

    I am trying to calculate the number of elements of an array that I pass as an argument to a function but I am not getting what I thought I should get.
    I am using sizeof(array)/sizeof(array[0]) both inside and outside the function and I am getting different answers for each one.

    Code:
    
    
    #include <stdio.h>
    #include <math.h>
    
    
    void calculateSize(float array[]);
    
    
    int main(int argc, const char * argv[]) {
    
        float balance[] = {10, 100, 500, 400};
    
    
    
        int size = sizeof(balance)/sizeof(balance[0]);
    
        printf("Outside function        size: %d\n\n",size);
    
    
        calculateSize(balance);
    
        return 0;
    }
    
    
    void calculateSize(float array[]){
    
        int size = sizeof(array)/sizeof(array[0]);
        printf("Inside function         size: %d\n\n",size);
    }
    
    
    I am getting as result:
    Outside function size: 4


    Inside function size: 2



    Does any of you know why this is happening? Also, which approach should I take to avoid this?

    Thank you very much in advance,
    Haecifer

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Despite how it appears, a complete array cannot be passed to a function - just a pointer to its first element.

    Question 6.21

    Also, which approach should I take to avoid this?
    It's good practice to pass the size of the array to the function along with the array itself.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sizeof function and pointers
    By johnmerlino in forum C Programming
    Replies: 2
    Last Post: 04-07-2014, 05:03 AM
  2. Replies: 3
    Last Post: 10-15-2012, 10:53 PM
  3. Newb Question concerning sizeof() function
    By Moe45673 in forum C Programming
    Replies: 7
    Last Post: 07-20-2011, 06:47 AM
  4. sizeof function
    By chrismiceli in forum C Programming
    Replies: 10
    Last Post: 02-28-2004, 08:28 PM
  5. SizeOf function
    By vanilly in forum C Programming
    Replies: 4
    Last Post: 02-13-2003, 12:18 PM

Tags for this Thread