Thread: Multidimensional struct array help

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    43

    Multidimensional struct array help

    It's been a long time since I've sat at the computer as a programmer, so pardon me if this is programming 101.

    What I've got is an array of structs, something like this:

    Code:
    struct Note
    {
        int nPitch;
        int nDuration;
    };
    
    Note noteMelody[4][10];
    1) I have a function that writes random data to each member of each struct in the array. The question is, how do I pass the struct to this function? Do I just need a refresher course on calling by reference?

    2) Can I adjust the size of the array at runtime?

    3) Is there a better way to do this than an array of structs? The thing is, each row of the array is one continuous chunk of data (as interpreted) - much like a train. So, I'm going to want to be able to swap, say, position [2][4] with [3][4]. Is this a job for linked lists?

    Thank you in advance for your help.

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    You can use a vector instead of an array. http://www.cprogramming.com/tutorial/stl/vector.html

    Just the day before yesterday I was talking with someone about Douglas Adams
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    1) Just use the same declaration for the parameter as you did for the variable itself: void foo(Note noteMelody[4][10]);

    2) Not with that kind of array, at least in standard C++ (gcc has an extension that might allow you to do that). You'd have to use a dynamic array, although I agree with Mario F. that using vector is a much better idea than using a dynamic array.

    3) Perhaps, but better could mean a bunch of different things. I would just start with a vector of structs. You can swap elements in a vector or array easily if they are copyable like your struct is.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with linked list sorting function
    By Jaggid1x in forum C Programming
    Replies: 6
    Last Post: 06-02-2009, 02:14 AM
  2. Writing an array of struct to file
    By stellastarr in forum C Programming
    Replies: 10
    Last Post: 03-25-2006, 06:59 PM
  3. Array of struct pointers - Losing my mind
    By drucillica in forum C Programming
    Replies: 5
    Last Post: 11-12-2005, 11:50 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. memory allocation for flexible array member of struct
    By jcarouth in forum C Programming
    Replies: 3
    Last Post: 09-11-2005, 12:19 PM