Thread: Determine array size

  1. #1
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164

    Determine array size

    I have an array of structures which is constantly changing size.

    How do I find out how many elements are in the array at any given time?

    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You maintain a separate variable containing the count of the number of elements.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >How do I find out how many elements are in the array at any given time?
    Save the size to a variable and use that when you need the current size. Or you could wrap your array in a class that maintains the size. Or you could save yourself the effort and use a vector.
    My best code is written with the delete key.

  4. #4
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    I assume this is in reference to your other thread, and so you cannot simply save the size because you don't know the size. Well, actually, in the code in that thread, the array of structures is not constantly changing size -- it is always 125. Your problem is that you need to know how many structures are read in during the fread to know how many of the actual structures have valid data.

    One way to do it is to provide a default constructor for your struct and set the code equal to -1 or some number that can never be valid. Then, when you loop through the structures you exit when the index is 125 or higher or when the code is the invalid number you set it to in the constructor. Of course, you would then have to check that the user doesn't enter -1 (or whichever number you pick) as the code when creating the structures, but I assume at some point you were going to validate the user input anyway.

    In fact, you should really be using a constructor to set default values for all your fields, since you write out 125 structures whether or not they have valid data.

    [EDIT] It looks like grib pointed out a good way to fix this in the other thread.

    P.S. If you weren't referring to the other thread then I'm sorry for the assumption and you might want to post a little more detail.

  5. #5
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    salem, I don't have the option to keep a counter running on them. chunks are bieng inserted and removed and I am unable to keep track of them.

    Prelude, sorry, I don't quite understand what meant. I'm new to programming. Can you explain with a bit of code please.

    If I have
    Code:
    struct MyStruct
    {
      /*members*/
    } MyArray[100];
    and I have data going in and out of them all them time, is there an algorithm/method with which I could query how many elements I have in my array at any given time?

    Something like what we have for quering int arrays
    Code:
    arraylen = sizeof(array) / sizeof(array[0])

    Thanks

  6. #6
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Code:
    struct MyStruct
    {
      /*members*/
    } MyArray[100];
    This is a static sized array, it always has 100 elements. You can use the sizeof trickery to instruct the compiler to get that information for you.

    If you're talking about knowing how many of the array elements are "used", then that's up to you to determine yourself. There's a way I can suggest, let me know if this is what you mean and I'll explain.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  7. #7
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    yes, thats what I'm after.
    I need to know how many of those 100 elements have data in them.

    Thanks

  8. #8
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Well, they all have data in them, technically speaking. You're after knowing which ones you program has put data into.

    You can do something like this:

    Code:
    #include <iostream>
    
    struct S
    {
      int State;
      int Data;
    };
    
    int main(void)
    {
      S s[100] = {{0,0}};
      
      s[0].State = 1;   // Mark this element as "in use"
      s[0].Data  = 99;
      
      s[0].State = 0;   // Mark this element as "not in use"
      
      return(0);
    }
    Of course, constructors and member functions would be a better way to go, but the concept is basically the same. I see jlou has already mentioned this type of thing.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  9. #9
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    How would you implement this structure in my code?

    This might be a dumb question, I do understand structures, but have only been learning for about 3 months, so I still need my hand held a little.

    Thanks

  10. #10
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>How would you implement this structure in my code?
    Pretty much like I did, but without seeing what you're actually trying to do, it's a little hard to guide you.

    How about making a function that "gets" the next free element for you, and one that frees it.
    Code:
    #include <iostream>
    
    struct S
    {
      int State;
      int Data;
    };
    
    int GetFreeItem(struct S s[], size_t Len)
    {
      size_t i;
      
      for (i = 0; i < Len; i++)
      {
        if (s[i].State == 0)
        {
          s[i].State = 1;
          return i;
        }
      }
      return -1;
    }
    
    void FreeItem(struct S s[], int Index)
    {
      s[Index].State = 0;
    }
    
    int main(void)
    {
      S s[100] = {{0,0}};
      int FreeIndex;
      
      if ((FreeIndex = GetFreeItem(s, sizeof(s)/sizeof(*s))) != -1)
      {
        s[FreeIndex].Data = 99;
      }
    
      FreeItem(s, FreeIndex);
          
      return(0);
    }
    But now we're running close to becoming a class, which would be a better design.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  11. #11
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    Thanks for the help.

    Gonna give myself a day with no questions to research this and try and implement it into my code alone.

    could be back with this though if it gets too much....heh

  12. #12
    Registered User
    Join Date
    Nov 2002
    Posts
    126
    Yarg! C++ programmers don't have to do this sort of thing...

    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    
    typedef struct { //MyStruct
    
    	int whatever;
    
    } MyStruct ;
    
    
    
    int main() {
    
    	//A vector is an array that grows naturally
    	
    	//This creates an empty vector that holds elements of MyStruct pointers
    	vector<MyStruct*> testvec;
    	
    	//Or if you wanted to initialize it with a size of 100 elements...
    	//vector<MyStruct*> testvec(100);
    	
    	//To add something on to the end of the vector, use push_back()
    	testvec.push_back( new MyStruct );
    	
    	MyStruct teststruct;
    	teststruct.whatever = 15;
    	
    	testvec.push_back( &teststruct );
    	
    	//You can access each element just like you can with an array
    	cout <<testvec[1]->whatever <<endl;
    	
    	//It knows its own size
    	cout <<testvec.size() <<endl;
    	
    	
    }
    Vectors also have methods for inserting and deleting elements. Search for "C++ STL vectors" on google and you'll find more about them.

  13. #13
    Registered User trainee's Avatar
    Join Date
    Jan 2004
    Posts
    32
    Yes, I was just going to mention vectors, as PorkyChop already did. If you need further help with them, post.

    trainee

  14. #14
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    I absolutely agree that vectors are better than arrays for C++. However, eth0, it appears that your instructor is teaching C++ using many C techniques. The techniques you show in the code in your other thread would not work well if stored as objects in a vector (they include a char array that would be copied incorrectly). If you use PorkyChop's method of holding pointers to objects, you must be careful to delete any pointers that are created with new (for example, the sample code PorkyChop provided has a memory leak).

    My suggestion if you are serious about C++, is to make the effort to learn C++ (as opposed to C with a C++ compiler). Either get your instructor to teach C++ programming (which is unlikely to happen) or take the time to learn it yourself.

    Once you feel you've got the assignment done to the instructor's specifications, I'd suggest learning about classes. They are basically the same as structs in C++, but the things you should learn about are constructors, destructors, copy constructors, assignment operators, access specifiers, etc. These things don't exist in C structs. Effective use of those would have made your problem a lot easier. Well written classes also work with vectors and other standard containers nicely and relatively easily.

    Good luck.

  15. #15
    Registered User eth0's Avatar
    Join Date
    Dec 2003
    Posts
    164
    Thanks for the tip with the vectors. I will research that method today. Probably be back with questions though
    However, does the vector route not require that you keep a running total of how many elements are in the array?

    jlou, I am already going down the route you suggested.

    I am very determined to learn this lanuage, however it is very difficult to learn with books alone.

    I am probably spending around 8 hours a day now trying to learn this. If I worked at a company with programmers, I know I could learn this in a quater of the time, as an experienced programmer to refer to when your stuck, can mean the difference between 10 minutes and 1 week. Even then at the end of the week your still uncertain yu tackled something in the best way.

    I will deffinitely achieve this, i'm just trying to stress how difficult it is when you are on your own. People post code and solutions on here without explaining, which just goes totaly over your head. All part of the fun though
    Last edited by eth0; 01-07-2004 at 02:15 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to determine length of pointer array
    By Dr.Zoidburg in forum C Programming
    Replies: 12
    Last Post: 02-16-2009, 06:52 PM
  2. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  3. Determine length of an array
    By ulillillia in forum C Programming
    Replies: 7
    Last Post: 04-21-2007, 08:32 PM
  4. An exercise in optimization
    By Prelude in forum Contests Board
    Replies: 10
    Last Post: 04-29-2005, 03:06 PM