How can I get the size of an input array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Arepi
    New Member
    • Sep 2008
    • 62

    #1

    How can I get the size of an input array

    Hi,

    I tried the following code:

    Code:
    void SizeArray(int t[]){
    	cout << "Size of the input array: " << sizeof(t) << endl;
    }
    void main(void){
        int arr[20];
        SizeArray(arr);
    }
    It gives 4 as result instead 80. As I see in this case the "t" variable behaves like a pointer. My question is: how can I get the real size(80) of the input array?

    Thanks

    Arepi
    Last edited by Arepi; Sep 11 '10, 12:45 PM. Reason: close brace
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The sizeof operator gives yiou the soze of the variable
    Code:
    on the stack
    .

    Therefore:

    Code:
    int arr[20];
          sizeof(arr);
    will have a sizeof 80 since the array is local (on the stack). The 80 is 20 x 4 assuming int is 4 bytes.

    However:

    Code:
    void function(int arr[20])
    {
       sizeof(arr);
    }
    will show arr with a sizeof 4.

    This is because the name of an array is the address of element 0. In the function, the argument is the address of an array of 20 int. It is the sizeof the address you see. Addresses are 4 bytes in 32-bit operating systems.

    I suggest you go to the C/C++ Insights forum and read the article Arrays Revealed where all this is explained.

    Comment

    • Arepi
      New Member
      • Sep 2008
      • 62

      #3
      Thanks,
      I know that in main it gives 80 and I mentioned in the function it behaves like a pointer.
      Well I have to ask other: Can I anyway get the size of the elements wich ones pointed by a pointer or is possible give an array as real array for the function as argument?
      I want get the size of input array in the given function(For example: I want read all elemnts of the array one by one that is why I need how long is the aray). Is it possible other then I solve the size in main and use this size as a second argument of the function?

      Thanks

      Arepi

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        The customary solution is to pass the function the address of element 0 of the array plus a second argument for the number of elements (not the size of the array).

        Old C libraries used and array of char as a special case. They passed the address of element 0 cas a char* and the function processed elements until it reached a binary 0 (\0) and then it stopped. This special array is called a C string.

        You could structure your own array so that the last element of the array was some special value and then you could test for the element rather than passing the number of elments as a second argument.

        Comment

        Working...