Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Is it "ok" to get array length this way

Is it "ok" to get array length this way

Scheduled Pinned Locked Moved C / C++ / MFC
csharpvisual-studiodata-structures
12 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F FocusedWolf

    #include iostream; //can't paste the << >> things here #include string; int main() { //works, from what i can see, because you cant compile "int someArray[] = {}" or "int arr[0];" because you cant allocate a 0-length array according to vs.net errors. So your guarenteed atleast 1 item in the array for "sizeof(_array[0])" to always find an item. this is the alternative to doing sizeof(int) or passing the type of the array to the macro. #define ARRAY_LENGTH(_array) (sizeof(_array)/sizeof(_array[0])) int someArray[] = {1, 2, 3, 4}; for(int i = 0; i < ARRAY_LENGTH(someArray); i++) { std::cout<<*(someArray + i)<

    N Offline
    N Offline
    norish
    wrote on last edited by
    #2

    ARRAY_LENGTH macro is always ok for real array but not for pointer. By the way, ARRAYSIZE() macro is predefined in windows.h of some newer sdk and it looks the same form as above. :)

    F 1 Reply Last reply
    0
    • F FocusedWolf

      #include iostream; //can't paste the << >> things here #include string; int main() { //works, from what i can see, because you cant compile "int someArray[] = {}" or "int arr[0];" because you cant allocate a 0-length array according to vs.net errors. So your guarenteed atleast 1 item in the array for "sizeof(_array[0])" to always find an item. this is the alternative to doing sizeof(int) or passing the type of the array to the macro. #define ARRAY_LENGTH(_array) (sizeof(_array)/sizeof(_array[0])) int someArray[] = {1, 2, 3, 4}; for(int i = 0; i < ARRAY_LENGTH(someArray); i++) { std::cout<<*(someArray + i)<

      S Offline
      S Offline
      Stuart Dootson
      wrote on last edited by
      #3

      If you want a type-safe mechanism for getting the number of elements in an array, you might consider this:

      #include <iostream>

      template<class A, size_t N>
      inline size_t ArraySize(const A ( & )[N]) { return N; }

      // Determine array size from an array type -
      // code from http://heifner.blogspot.com/2008/04/c-array-size-determination-part-2.html
      template <typename T>
      struct array_info
      {
      };

      template <typename T, size_t N>
      struct array_info<T[N]>
      {
      typedef T type;
      enum { size = N };
      };

      int main()
      {
      typedef int (MyArray)[120];
      int a[120];
      float b[120];
      std::cout << ArraySize(a) << std::endl;
      std::cout << ArraySize(b) << std::endl;
      std::cout << array_info<MyArray>::size << std::endl;
      }

      Here you have mechanisms for getting the number of elements in an array variable (function ArraySize) or an array type (struct array_info). And (unlike the macro version) these two won't compile if given a pointer variable/type - the power of pattern matching sees to that :-)

      Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

      C 1 Reply Last reply
      0
      • S Stuart Dootson

        If you want a type-safe mechanism for getting the number of elements in an array, you might consider this:

        #include <iostream>

        template<class A, size_t N>
        inline size_t ArraySize(const A ( & )[N]) { return N; }

        // Determine array size from an array type -
        // code from http://heifner.blogspot.com/2008/04/c-array-size-determination-part-2.html
        template <typename T>
        struct array_info
        {
        };

        template <typename T, size_t N>
        struct array_info<T[N]>
        {
        typedef T type;
        enum { size = N };
        };

        int main()
        {
        typedef int (MyArray)[120];
        int a[120];
        float b[120];
        std::cout << ArraySize(a) << std::endl;
        std::cout << ArraySize(b) << std::endl;
        std::cout << array_info<MyArray>::size << std::endl;
        }

        Here you have mechanisms for getting the number of elements in an array variable (function ArraySize) or an array type (struct array_info). And (unlike the macro version) these two won't compile if given a pointer variable/type - the power of pattern matching sees to that :-)

        Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

        C Offline
        C Offline
        Chris Losinger
        wrote on last edited by
        #4

        or... std::vector

        image processing toolkits | batch image processing

        F S 2 Replies Last reply
        0
        • N norish

          ARRAY_LENGTH macro is always ok for real array but not for pointer. By the way, ARRAYSIZE() macro is predefined in windows.h of some newer sdk and it looks the same form as above. :)

          F Offline
          F Offline
          FocusedWolf
          wrote on last edited by
          #5

          wow norish i had no idea about that macro :P when i read that sizeof returned the number of bytes used by an array, i figured if i just divided by the size of the datatype used that i could get the length.

          1 Reply Last reply
          0
          • C Chris Losinger

            or... std::vector

            image processing toolkits | batch image processing

            F Offline
            F Offline
            FocusedWolf
            wrote on last edited by
            #6

            hmm vectors? i suppose. Is it possible that arrays are more efficient? Now this part of the code is really sexy: template inline size_t ArraySize(const A ( & )[N]) { return N; } int main() { int a[120]; std::cout << ArraySize(a) << std::endl; } i'm not sure how it works but my guess is that somehow it's magically reading the size from the declaration of the array.

            S 1 Reply Last reply
            0
            • F FocusedWolf

              #include iostream; //can't paste the << >> things here #include string; int main() { //works, from what i can see, because you cant compile "int someArray[] = {}" or "int arr[0];" because you cant allocate a 0-length array according to vs.net errors. So your guarenteed atleast 1 item in the array for "sizeof(_array[0])" to always find an item. this is the alternative to doing sizeof(int) or passing the type of the array to the macro. #define ARRAY_LENGTH(_array) (sizeof(_array)/sizeof(_array[0])) int someArray[] = {1, 2, 3, 4}; for(int i = 0; i < ARRAY_LENGTH(someArray); i++) { std::cout<<*(someArray + i)<

              D Offline
              D Offline
              David Crow
              wrote on last edited by
              #7

              FocusedWolf wrote:

              #include iostream; //can't paste the << >> things here #include string;

              Why not?

              #include <iostream>
              #include <string>

              Did you use the < button above the smileys?

              "Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown

              "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

              F 1 Reply Last reply
              0
              • F FocusedWolf

                hmm vectors? i suppose. Is it possible that arrays are more efficient? Now this part of the code is really sexy: template inline size_t ArraySize(const A ( & )[N]) { return N; } int main() { int a[120]; std::cout << ArraySize(a) << std::endl; } i'm not sure how it works but my guess is that somehow it's magically reading the size from the declaration of the array.

                S Offline
                S Offline
                Stuart Dootson
                wrote on last edited by
                #8

                FocusedWolf wrote:

                possible that arrays are more efficient

                Nope - in VS2008, vectors are guaranteed to use contiguous storage (i.e. same as arrays).

                FocusedWolf wrote:

                i'm not sure how it works but my guess is that somehow it's magically reading the size from the declaration of the array.

                That's the one. You pass an array and the compiler instantiates the function with the template parameters appropriate for that array.

                Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                F 1 Reply Last reply
                0
                • C Chris Losinger

                  or... std::vector

                  image processing toolkits | batch image processing

                  S Offline
                  S Offline
                  Stuart Dootson
                  wrote on last edited by
                  #9

                  Not always necessarily better - not until C++ 0x when vectors get array style initialisers (IIU&RC). Say I have an encryption key that (foolishly) I'm hardcoding in the software - which is simpler: [edit]Or a better example - say I'm implementing a CRC32, which can be highly optimised by using a static array of byte values[/edit]

                  const BYTE key[] = { 12, 34, 4, 5, 36, 23, 765, 34 };

                  std::vector vKey;
                  vKey.push_back(12);
                  : :
                  vKey.push_back(34);

                  Yes, I know Boost has a library[^] that almost gives vectors initialiser syntax...but sometimes you just can't be bothered :-)

                  Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                  1 Reply Last reply
                  0
                  • F FocusedWolf

                    #include iostream; //can't paste the << >> things here #include string; int main() { //works, from what i can see, because you cant compile "int someArray[] = {}" or "int arr[0];" because you cant allocate a 0-length array according to vs.net errors. So your guarenteed atleast 1 item in the array for "sizeof(_array[0])" to always find an item. this is the alternative to doing sizeof(int) or passing the type of the array to the macro. #define ARRAY_LENGTH(_array) (sizeof(_array)/sizeof(_array[0])) int someArray[] = {1, 2, 3, 4}; for(int i = 0; i < ARRAY_LENGTH(someArray); i++) { std::cout<<*(someArray + i)<

                    G Offline
                    G Offline
                    gethomast
                    wrote on last edited by
                    #10

                    see the _countof macro in the Run-Time Library Reference

                    1 Reply Last reply
                    0
                    • D David Crow

                      FocusedWolf wrote:

                      #include iostream; //can't paste the << >> things here #include string;

                      Why not?

                      #include <iostream>
                      #include <string>

                      Did you use the < button above the smileys?

                      "Old age is like a bank account. You withdraw later in life what you have deposited along the way." - Unknown

                      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                      F Offline
                      F Offline
                      FocusedWolf
                      wrote on last edited by
                      #11

                      Hmm: #include <iostream> #include <string> O i see... if this works then the lt,gt things are auto replacing my < >. Ya didn't realize that yesterday lol

                      1 Reply Last reply
                      0
                      • S Stuart Dootson

                        FocusedWolf wrote:

                        possible that arrays are more efficient

                        Nope - in VS2008, vectors are guaranteed to use contiguous storage (i.e. same as arrays).

                        FocusedWolf wrote:

                        i'm not sure how it works but my guess is that somehow it's magically reading the size from the declaration of the array.

                        That's the one. You pass an array and the compiler instantiates the function with the template parameters appropriate for that array.

                        Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                        F Offline
                        F Offline
                        FocusedWolf
                        wrote on last edited by
                        #12

                        Thanks for that info.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups