Passing Class Array through Fucntion

This is a discussion on Passing Class Array through Fucntion within the C++ Programming forums, part of the General Programming Boards category; I made a class called Box, which has a size of 100 . Then I made an array of 6 ...

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    66

    Passing Class Array through Fucntion

    I made a class called Box, which has a size of 100 . Then I made an array of 6 "Boxes" , now, the size if 600. However, when I pass this array into a function, and tries to use sizeof in the function, the size of the whole array becomes 4, how come?
    An Unofficial Cristiano Ronaldo Website : Ronaldo 7

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Because C++ passes an array as a pointer to the first element. When you use sizeof, you're getting the size of a pointer, not an array. One solution is to pass the size as well:
    Code:
    void f ( Box array[], size_t size );
    Or encapsulate the array ina class or structure and pass a reference to that:
    Code:
    struct BoxArray {
      Box array[SIZE];
      size_t size;
    };
    
    void f ( BoxArray& ba );
    Or even pass a reference to the array. But then you have size limitations that you must adhere to:
    Code:
    void f ( Box (&array)[10] );
    Last edited by Prelude; 03-07-2004 at 07:19 PM.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    66
    Originally posted by Prelude
    Because C++ passes an array as a pointer to the first element. When you use sizeof, you're getting the size of a pointer, not an array. One solution is to pass the size as well:
    Code:
    void f ( Box array[], size_t size );
    Or encapsulate the array ina class or structure and pass a reference to that:
    Code:
    struct BoxArray {
      Box array[SIZE];
      size_t size;
    };
    
    void f ( BoxArray& ba );
    Or any of a number of other ways. But passing the size along with the array is the simplest.
    ahh, okay, thx.
    An Unofficial Cristiano Ronaldo Website : Ronaldo 7

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 08:39 AM
  2. pointer of array of class
    By 11moshiko11 in forum C++ Programming
    Replies: 5
    Last Post: 04-05-2008, 10:58 AM
  3. function passing argument..array ?
    By jochen in forum C Programming
    Replies: 2
    Last Post: 09-30-2007, 12:53 PM
  4. An Array of Classes in a different Class
    By mas0nite in forum C++ Programming
    Replies: 4
    Last Post: 10-05-2006, 03:28 PM
  5. Passing array through class constructor
    By sonicdoomx in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2006, 02:42 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21