Thread: How get size of every dimension in array?

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    184

    How get size of every dimension in array?

    If I have a method:

    Code:
    public void do(int[][] num);
    How would I loop through every dimension in the multi-dimensional array? In other words, how do I find the size(s)?

    In java i can do:

    Code:
    for ( int i = 0; i < num.size(); i++ )
    what do I do in c++?

    Thanks!

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    With native arrays, you can't. However, if you std::vector, you can indeed via the member size().
    All you might need to do is:
    std::vector< std::vector<int> >
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You can find out the size of an array if you can access the original array itself. However, passing an array to a function means that you can't tell how big the array is inside the function. So you have to pass the size of the array to the function.

    Also, all but the leftmost array element has to have a size in it.

    To get the number of elements in an array, use sizeof(array)/sizeof(*array) (or array[0] instead of *array). Note that this works for arrays with any arbitrary number of dimensions. For example:
    Code:
    int array[2][3][4];
    size_t x = sizeof(array) / sizeof(*array);  /* = 2 */
    size_t x2 = sizeof(array) / sizeof(array[0]);  /* = 2 */
    size_t y = sizeof(*array) / sizeof(**array);  /* = 3 */
    size_t y2 = sizeof(array[0]) / sizeof(array[0][0]);  /* = 3 */
    size_t z = sizeof(**array) / sizeof(***array);  /* = 4 */
    size_t z = sizeof(array[0][0]) / sizeof(array[0][0][0]);  /* = 4 */
    Anyway -- here's food for thought.
    Code:
    #include <iostream>
    
    void print_array(int array[3][3]);
    void print_any_array(int array[], size_t elements);
    void print_2D_array(int array[][3], size_t elements);
    
    int main(void) {
        int array[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    
        print_array(array);
        print_2D_array(array, sizeof(array) / sizeof(*array));
    
        return 0;
    }
    
    void print_array(int array[3][3]) {
        for(int x = 0; x < 3; x ++) {
            for(int y = 0; y < 3; y ++) {
                std::cout << array[x][y] << ' ';
            }
            std::cout << std::endl;
        }
    }
    
    void print_any_array(int array[], size_t elements) {
        for(size_t i = 0; i < elements; i ++) {
            std::cout << array[i] << ' ';
        }
    }
    
    void print_2D_array(int array[][3], size_t elements) {
        for(size_t i = 0; i < elements; i ++) {
            print_any_array(array[i], 3);
            std::cout << std::endl;
        }
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Weak. dra's Avatar
    Join Date
    Apr 2005
    Posts
    166
    Well for starters, in C++, you need to specify the size of one of the dimensions. Then I guess you could use the sizeof keyword or simply ask for the size of the other dimension as a function argument.

    Code:
    #include <iostream>
    
    int main(int argc, char* argv[]){
    
      int two_dim[1][1];
    
      int size = sizeof(two_dim)/sizeof(*two_dim);
    
      std::cout << size;
    
      return 0;
    
    }
    
    //prints 1

    But since you're in C++, why not use vectors/lists? They have functions like size() that makes it much easier.

    EDIT: oh wow you guys are fast =P.
    Last edited by dra; 03-21-2008 at 04:39 PM.

  5. #5
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Something I forgot to mention which this reminded me of:
    Code:
    int size = sizeof(two_dim[0])/sizeof(*two_dim[0]);
    sizeof() actually evaluates to a value of type size_t, not int. However, many people don't like typing "size_t" all of the time, so you can use int if you like. You'll only run into trouble with really, really long strings.

    Your compiler might warn about signed/unsigned type mismatches, however. If it does, and you care, you could use
    Code:
    int size = (int)(sizeof(two_dim[0])/sizeof(*two_dim[0]));
    or better yet, size_ts.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  6. #6
    Registered User
    Join Date
    Nov 2006
    Posts
    184
    Thanks for all the great replies!

    A couple points and questions:

    1. The reason why I don't use vectors is that I can't dictate that in my code. I have to use what i'm getting from a third party's code and they use stuff like "int[][][]."

    2. If you can use sizeof() sometimes, why can't you use it all the time? I don't understand why it works for a 1-dimensional array, or for "some" dimensions but not all dimensions. Can someone explain this to me?

    3. Why can't I pass an "unknown" array by reference?
    Last edited by 6tr6tr; 03-21-2008 at 05:20 PM.

  7. #7
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    1. That's invalid, so it's unlikely that you're looking at it.
    2. http://c-faq.com/aryptr/pass2dary.html
    3. See #1.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #8
    Registered User
    Join Date
    Nov 2006
    Posts
    184
    Quote Originally Posted by Dave_Sinkula View Post
    1. That's invalid, so it's unlikely that you're looking at it.
    2. http://c-faq.com/aryptr/pass2dary.html
    3. See #1.
    It's not invalid. You can define the following function:

    void do(int arg[][][]);

    That's completely valid in C++ and that's what I've been given to work with (they're interfaces that are expected and data is passed to them from other code).

  9. #9
    Registered User
    Join Date
    Mar 2008
    Posts
    2
    Quote Originally Posted by 6tr6tr View Post
    It's not invalid. You can define the following function:

    void do(int arg[][][]);

    That's completely valid in C++ and that's what I've been given to work with (they're interfaces that are expected and data is passed to them from other code).
    what compiler are you using? when i try to compile that, i get this:

    5 C:\Documents and Settings\Owner\My Documents\c++ programs\untitled14.cpp declaration of `a' as multidimensional array must have bounds for all dimensions except the first

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by 6tr6tr
    That's completely valid in C++ and that's what I've been given to work with (they're interfaces that are expected and data is passed to them from other code).
    From the 2003 edition of the C++ Standard (ISO/IEC 14882:2003), section 8.3.4:
    When several "array of" specifications are adjacent, a multidimensional array is created; the constant expressions that specify the bounds of the arrays can be omitted only for the first member of the sequence. [Note: this elision is useful for function parameters of array types, and when the array is external and the definition, which allocates storage, is given elsewhere. ]
    Take a look at what you claim to be valid:
    Code:
    void do(int arg[][][]);
    The constant expressions are omitted from all three "array of" specifications. The standard only allows the first one to be omitted. Therefore your claim is incorrect.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by 6tr6tr View Post
    2. If you can use sizeof() sometimes, why can't you use it all the time? I don't understand why it works for a 1-dimensional array, or for "some" dimensions but not all dimensions. Can someone explain this to me?
    You can get the size of all dimensions. However, you can't get the size of an array once passed to a function because arrays are passed as pointers.

    Quote Originally Posted by 6tr6tr View Post
    3. Why can't I pass an "unknown" array by reference?
    You cannot pass an array of unknown dimensions because the compiler wouldn't be able to generate correct code, for one thing.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    See, in C and C++, arrays are very low-level things. They're just a big chunk of contiguous memory. 1D arrays are the easiest to visualize. For an array of ten elements, you just allocate ten times the size of one element. Because C++ doesn't do bounds checking, you can just pass the address of the first part of this memory to a function. As long as you know the size of each element -- and you do, because they have a specified type, say "int" -- then the function can calculate the position of each element in the array. The function doesn't know that there are only ten elements and lets you try to access element 15, but that's what C++ does.

    But when you have more than one dimension, it gets more complicated. With
    Code:
    int array[3][4];
    array[0] is just like a 1D array. Each element (array[0][x]) is the size of an int.

    But array[1] has to start counting at one past the last element of array[0]. Remember, arrays are contiguous memory. In order to do this, it needs to know how big array[0] was. In effect, since array[0][3] is the last element of array[0], array[1][0] is like array[0][4].

    In order for a called function to calculate where array[1][0] actually refers to, it needs to know how many elements are in array[0]. It needs to be passed "int array[][4]", which gives it all the information it needs. Each element is the size of an int. And each first-level element of array (like array[0]) has 4 elements; so array[1][2] is sizeof(int)*(4 * 1 + 2) bytes beyond the first element of the array.

    *sees confusion* Look, I haven't explained it very well. If you're interested, consider consulting Wikipedia or a textbox.

    Anyway, in Java, arrays are just objects. Internally, they're probably stored the same way or similarly (maybe not contiguous, who knows). But the array object stores the dimensions of itself, so functions can still find the same information without you having to tell it how big the various dimensions of the array are.

    C and C++'s philosophy emphasizes efficiency, which is why they do this as they do. Java has a much greater emphasis on security and usability. So, for example, a Java array will tell you when you go outside its bounds, and it much easier to pass around. But a C++ array uses less memory and less execution time. Ease of use is the price you pay for efficiency.

    C++ folks, of course, don't always want this efficiency at the cost of usability, which is why STL containers like vectors were invented. You'll find them much easier to use, because they're very similar to Java's arrays.

    I do suggest you learn about arrays sometime, however. They're very widely used.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  2. Array size
    By tigrfire in forum C Programming
    Replies: 5
    Last Post: 11-14-2005, 08:45 PM
  3. An exercise in optimization
    By Prelude in forum Contests Board
    Replies: 10
    Last Post: 04-29-2005, 03:06 PM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Maximum array size?
    By code2big in forum C Programming
    Replies: 2
    Last Post: 05-25-2004, 08:16 AM