CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Jun 2006
    Location
    Germany
    Posts
    103

    Get the size of an struct array?

    Hello,
    how to get the item count of an array of structs?
    For example:
    Code:
    struct intArr
    {
    int i;
    int y;
    }
    intArr ar[10]; // here!
    sizeof(ar) is wrong!?

    thanks
    break;

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Get the size of an struct array?

    Quote Originally Posted by break;
    Hello,
    how to get the item count of an array of structs?
    For example:
    Code:
    struct intArr
    {
    int i;
    int y;
    }
    intArr ar[10]; // here!
    sizeof(ar) is wrong!?

    thanks
    break;
    Code:
    sizeof(ar) / sizeof(ar[0]);
    This only works if the code is placed where "ar" is really an array, not a pointer.

    It will not work if you pass "ar"' to a function, and you attempt to get the number of elements from the passed in parameter. Passing an array to a function just passes a pointer, not the entire array.

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Jun 2006
    Location
    Germany
    Posts
    103

    Re: Get the size of an struct array?

    Hello,
    thanks for your help!

    regards
    break;

  4. #4
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,234

    Re: Get the size of an struct array?

    [ Moved thread ]

  5. #5
    Join Date
    Dec 2003
    Location
    Middletown, DE
    Posts
    67

    Re: Get the size of an struct array?

    I like this method better:
    Code:
    sizeof(ar) / sizeof(intArr)

  6. #6
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: Get the size of an struct array?

    Or you could use the Standard Template Library

    Code:
    #include <vector>
    
    struct intArr
    {
    int i;
    int y;
    }
    
    std::vector<intArr> ar(10);
    
    std::vector<intArr>::size_type size = ar.size();
    Last edited by JohnW@Wessex; March 16th, 2007 at 09:49 AM.

  7. #7
    Join Date
    Feb 2002
    Posts
    4,640

    Re: Get the size of an struct array?

    Quote Originally Posted by spoulson
    I like this method better:
    Code:
    sizeof(ar) / sizeof(intArr)
    Actually, I think that form is more confusing. Dividing the size of the entire array by the size of the first element is more intuitive.

    My $0.02..

    Viggy

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured