Calculating the size of an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fauxanadu
    New Member
    • Mar 2007
    • 60

    #16
    I'm not aggitated at what you said Laharl. It was a good point (and a good name to boot. Disgaea is a wonderful game!). I just responded that I don't like templates (it is a personal preference). I am aggitated at the fact that this other person comes along and starts in with the attacks against my character acting like I don't know jack about programming. Especially when i'm merely attempting to be helpful.

    Comment

    • oler1s
      Recognized Expert Contributor
      • Aug 2007
      • 671

      #17
      You need a thicker skin. To the OP's technical question, you proposed solutions that not only would be bad, but defended them with technically unacceptable arguments. When I get the chance, I'll go through your code completely, explain its flaws, and post them in a new thread.

      EDIT: To be precise, I actually thought you were making an elaborate joke. Based on your next two responses, it seems like you were actually serious...

      Comment

      • Sirmont
        New Member
        • Jul 2008
        • 12

        #18
        You are absolutely right fauxanadu, this code here:

        std::vector<int > MyArray;

        is uglier than the 200 lines of code you wrote. What I suggest you do, to help ease the pain, is this:

        typdef std::vector<int > IntArray;
        IntArray MyArray;

        Although we doubled our initial code, which is barely acceptable, we are still under your 200 lines, which might, in the end be forgivable, when we do the float version of your class and ours....

        Let me try:
        typdef std::vector<flo at> FloatArray;
        FloatArray MyOtherArray;

        Woah, I'm exhausted.

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #19
          Originally posted by fauxanadu
          C) [ ... ] My reviews are always positive and I have nothing but praise from the higher ups about my results. So as you can see, your point is both flawed and meaningless.
          This subject certainly doesn't need a heated debate and most certainly not a
          non sequitur like this; as everybody knows (or should know) templates can
          cause code bloat as oler1s pointed out, just as your way of working; nothing
          personal here and nothing to get agitated about.

          Please keep this discussion a nice and technical one, not a personal one; for
          references read Weinberg's "egoless programming". Let the show continue ;-)

          kind regards,

          Jos (moderator)

          Comment

          • Nepomuk
            Recognized Expert Specialist
            • Aug 2007
            • 3111

            #20
            Woah, I hadn't expected anything like this, when I asked the question!

            Now, I'd like to say "Thank you!" to everybody, who took the time to go through the thread and to, eventually, find the best (or should I say "a best") solution to my request. Sometimes, it is overwhelming, how much thought and feelings people put into solving a problem.

            @oler1s: Thank you for trying to prevent me from doing anything utterly wrong, even if your comments were not in line with everyone's opinion.

            @arnaudk: Thank you again for your suggestion. As I said before, it's not an option for me, but certainly something to hold in mind for later occasions.

            @Laharl: Although you made suggestions towards the solution, I guess your main input to this Thread was: "Calm down!" ^^ Thanks for that and for your suggestions.

            @JosAH: OK, your reply #9 certainly helps me to understand the differences between C/C++ and Java.

            @fauxanadu: I haven't looked at your solution very much yet, but I certainly will - even if it should be badly structured (which I wouldn't be able to tell until I've had a good look at it), I'm sure, there's a lot I can learn from it.

            @Sirmont: Hm, that's an interesting idea. I'll think about that. It can certainly save a lot of typing at times.

            Now, I haven't used any of the solutions yet in the overall problem I'm trying to solve, but I guess I'll check a few out and then decide, which I like best for this task.

            Greetings,
            Nepomuk

            Comment

            • Banfa
              Recognized Expert Expert
              • Feb 2006
              • 9067

              #21
              Originally posted by nepomuk
              ... the best (or should I say "a best") solution
              I think the term you are looking for is "a solution" :D

              The term best is not required, it almost certainly breaks Joshs egoless programming paradigm and if you are going to say best then you are going to have to defined how you are judging best because the best solution will be dependent on circumstance. For instance the best solution to a given problem will be different given 1 week and infinite cash to the solution to the same problem given infinite time but only £100.

              Something I heard a year or so ago which I like was, for a given programming task the solution can have the following qualities (assuming that the solution is working correctly)

              It's Cheap
              It's Well Written
              It's Produced Quickly

              But it can only have 2 of those 3 qualities.

              Comment

              • JosAH
                Recognized Expert MVP
                • Mar 2007
                • 11453

                #22
                Originally posted by Banfa
                Something I heard a year or so ago which I like was, for a given programming task the solution can have the following qualities (assuming that the solution is working correctly)

                It's Cheap
                It's Well Written
                It's Produced Quickly

                But it can only have 2 of those 3 qualities.
                Nice one! IMHO most of the software has only one or less of those qualities ;-)

                kind regards,

                Jos

                Comment

                • oler1s
                  Recognized Expert Contributor
                  • Aug 2007
                  • 671

                  #23
                  If anyone (including Fauxanadu) wants to discuss something in private in relation to my posts in this thread, do PM me. Fauxanadu, I honestly thought you were either trolling or making a bad joke, so I realize you are severely offended when taking some of my remarks in earnest. However, my professional and technical criticism of your code, and programming statements, still remain. I expand on it here.

                  I'll begin my criticizing the code first. From top to bottom:

                  In IntArray.h:
                  Code:
                  #define NULL 0
                  Not necessary in C++. Just use 0 in it's place. Since it's preferable not to have defines, I consider using a define for NULL bad programming practice.

                  Code:
                  #include <stdio.h>
                  Deprecated in C++. Whatever your argument about deprecation, there's a big, big reason you don't want to do this in a header file. stdio.h works by bringing in cstdio, then including the entire namespace std. Since a using namespace std; in a header file is a definite no-no, this makes including stdio.h completely unacceptable.

                  Code:
                  class IntArray
                  Here, you have directly coupled the idea of an array to the int datatype. C++ has facilities to decouple the implementations , as the Boost.Array container has done. Therefore, your implementation already has a big black mark against it. What we want is a first class array object, that has type safety, as little overhead over a normal array, plays well with STL and general usage, and is highly reusable. Tight coupling is a huge strike, as you have not created a generic and reusable array type.

                  Ctors/Dtors:
                  No exception safety in allocation. No freeing of memory (!) (there's no dtor).

                  Copying array values:
                  I would have used std::copy. Why reimplement this portion?

                  delArray is bad:
                  It directly sets the pointer to 0 (no freeing the memory!).

                  Dubious implementation of getArray:
                  The point of your array object is to not have the programmer deal with a raw array. You want to wrap around this array and present a proper interface, not wrap and then give a bunch of set and get functions. You've done nothing but write bloat.

                  Unnecessary setArray:
                  Unneeded because that's what a ctor is for.

                  Dubious naming of sizeOf.
                  Can be confused with compile time sizeof operator. Not like normal STL containers, which would implement size().

                  Missing critical operators:
                  Like say, the subscript operator?

                  For Test.cpp

                  Use of defines instead of constant ints is C-ish code. You want to create actual constants, which are typesafe and dealt with the compiler, not the pre-compiler.

                  Code:
                  IntArray *myFirstArray;
                  IntArray *mySecondArray;
                  Dubious usage. One of the ideas behind a first class type is that the programmer doesn't have to deal with pointers that needs to be managed.

                  Usage of printf in C++. Why don't you use iostreams? Definitely more typesafe than the variadic printf.

                  Actually, that code is confusing because of cryptic usage of BASE, MULT, TOP, NEW, NEWS(!), and NEWL(!) macros.

                  Finally, this code implements no interface that works well with STL. No iterators. No common functions implemented by the other STL containers. That means I can't use std::copy or the like with your array type.

                  All around, an unusable container.

                  Comment

                  • oler1s
                    Recognized Expert Contributor
                    • Aug 2007
                    • 671

                    #24
                    Here, I criticize the rest of what Fauxanadu has said. It's all technical appraisal, so I hope this isn't taken as a ad hominem attack.

                    Despite it being depricated, it is still in rather common use (<stdio.h> that is).
                    It's in common use because of legacy code. Not because it is OK to keep using stdio.h on fresh codebases.

                    And as for templates, bleh. It makes all the code ugly with all those damned angled brackets and even longer names.
                    I don't believe so, but how is the aesthetic appeal of templates relevant?

                    You save time on the front end by not copying and pasting the code a few times for each type, but then you lose it on the backend having to type all those damn <double>s, <int>s and <whathaveyou> s on the backend everytime you use it your template.
                    You save a lot more when you use generics. Copy pasting code is bad because you exponentially increase maintainability . It increases the work you have to do. It bloats your codebase, because you have repeated yourself. Why are you, a programmer, doing repetitive work, when the computer should be doing it?

                    Plus, in regards to templates, a float and int are not always going to have the same member functions, so it would probably, in all honesty, be best to impliment it as a inherited heirarchy
                    Yet, the concept of an array is independent of the type. You don't want them to be coupled, providing interfaces instead for various operations. Besides, templates give you enormous flexibility in that you can have multiple orthogonal object policies resolved at compile time. Read Alexandrescu's "Modern C++" to see how he handles templates.

                    In your code, you suggest replacing all instances of int with float to get an array type that works with float. Does that not suggest that the member functions for this array type are independent of the type? Furthermore, creating object hierarchies is bad for two major reasons. The first is that you automatically introduce performance penalties unnecessarily. Hierarchies need to be resolved at runtime. Furthermore, it requires coupling. Everytime you want an array of a new type, you repeat code, inherit from some common base, and so on. You created a bloated object hierarchy, all of which involve repeated code. Does this sound appealing to you?

                    A) That code was written in about 5 minutes.
                    I could take 5 seconds to say "The Earth is flat." I could also take 1 year to form that statement. Regardless of how long, my statement is wrong. That you took under 5 minutes to write up the code is irrelevant. It's broken and unusable. If you don't want to be criticized for bad code, and don't want to come off as a bad coder, take the time to write proper code. This is a technical forum, and technical accuracy is valued.

                    Each person has their coding preference. Mine is against templates.
                    One does not have preferences in programming like one prefers colors, or ice cream. A programmer needs to make choices based on technical reasons.
                    They are, to say the least, ugly and make the code far more difficult to read. There are many paths to produce the same result.
                    There must be many paths to produce the same result. Because you have a generic container (multiple of one type) applied to infinitely many types. Your idea has programmers manually copying code (and thus code paths) for each type. Using a template has the computer do it. Is not your idea uglier, more difficult to read, far more difficult to maintain?

                    My job description...
                    Is irrelevant. Obviously, the reputation and knowledge of people carries weight in the argument. But it does not make it correct. Furthermore, do not expect that in a technical discussion, you will be shielded by reputation, past work, or titles.

                    Not only is it in wide use, but C++, by design, retains all of C in its specification.
                    No. C++ is not C. it is not C with a few things tacked on. It is a different language, that implements a subset of C. Therefore, there is very good compatibility with C code. However, it is not complete, and furthermore, idiomatic C code and C++ code differ. If you program C code with a C++ compiler, that's up to you. But it's not idiomatic C++.

                    Comment

                    • JosAH
                      Recognized Expert MVP
                      • Mar 2007
                      • 11453

                      #25
                      Just to be sure I post the following text verbatim here; just so that this thread
                      doesn't go out of hand.

                      kind regards,

                      Jos

                      --------------------------------------------------------------------------------

                      The following text is not mine; it's a summary of Henry Weinberg's essay on
                      egoless programming; read it and realize how true it all is.

                      The Ten Commandments

                      1) Understand and accept that you will make mistakes. The point is to find
                      them early, before they make it into production. Fortunately, except for the few
                      of us developing rocket guidance software at JPL, mistakes are rarely fatal in
                      our industry, so we can, and should, learn, laugh, and move on.

                      2) You are not your code. Remember that the entire point of a review is to find
                      problems, and problems will be found. Don't take it personally when one is
                      uncovered.

                      3) No matter how much "karate" you know, someone else will always know
                      more. Such an individual can teach you some new moves if you ask. Seek and
                      accept input from others, especially when you think it's not needed.

                      4) Don't rewrite code without consultation. There's a fine line between "fixing
                      code" and "rewriting code." Know the difference, and pursue stylistic changes
                      within the framework of a code review, not as a lone enforcer.

                      5) Treat people who know less than you with respect, deference, and patience.
                      Nontechnical people who deal with developers on a regular basis almost
                      universally hold the opinion that we are prima donnas at best and crybabies at
                      worst. Don't reinforce this stereotype with anger and impatience.

                      6) The only constant in the world is change. Be open to it and accept it with a
                      smile. Look at each change to your requirements, platform, or tool as a new
                      challenge, not as some serious inconvenience to be fought.

                      7) The only true authority stems from knowledge, not from position. Knowledge
                      engenders authority, and authority engenders respect—so if you want respect
                      in an egoless environment, cultivate knowledge.

                      8) Fight for what you believe, but gracefully accept defeat. Understand that
                      sometimes your ideas will be overruled. Even if you do turn out to be right, don't
                      take revenge or say, "I told you so" more than a few times at most, and don't
                      make your dearly departed idea a martyr or rallying cry.

                      9) Don't be "the guy in the room." Don't be the guy coding in the dark office
                      emerging only to buy cola. The guy in the room is out of touch, out of sight, and
                      out of control and has no place in an open, collaborative environment.

                      10) Critique code instead of people—be kind to the coder, not to the code.As
                      much as possible, make all of your comments positive and oriented to
                      improving the code. Relate comments to local standards, program specs,
                      increased performance, etc.

                      --------------------------------------------------------------------------------

                      Comment

                      • fauxanadu
                        New Member
                        • Mar 2007
                        • 60

                        #26
                        #define NULL 0
                        Not necessary in C++. Just use 0 in it's place. Since it's preferable not to have defines, I consider using a define for NULL bad programming practice.
                        That is a preference. Where I work, using defines is part of the code format standard, so it is what I use on a daily basis and that is what I am used to. Therefore it will show in what I code. Where I work, it is also not standard to use 0 as NULL for all procedures since some procedures use 0 for other things (I work with alot of legacy code).


                        #include <stdio.h>
                        Deprecated in C++. Whatever your argument about deprecation, there's a big, big reason you don't want to do this in a header file. stdio.h works by bringing in cstdio, then including the entire namespace std. Since a using namespace std; in a header file is a definite no-no, this makes including stdio.h completely unacceptable.
                        I've already stated that I see little problem with using stdio.h. I've conceded that it shouldn't be done, but again, I work with alot of legacy code, it's what I end up using alot, and it shows.

                        Here, you have directly coupled the idea of an array to the int datatype. C++ has facilities to decouple the implementations , as the Boost.Array container has done. Therefore, your implementation already has a big black mark against it. What we want is a first class array object, that has type safety, as little overhead over a normal array, plays well with STL and general usage, and is highly reusable. Tight coupling is a huge strike, as you have not created a generic and reusable array type.
                        I'm rather biased against generics as i've already stated. I feel they are quite ugly and are hard to read. They can also lead to code bloat.

                        Ctors/Dtors:
                        No exception safety in allocation. No freeing of memory (!) (there's no dtor).
                        I simply forgot a deconstructor (due to the aformentioned writing in 5 minutes). I accept this is a flaw.

                        Copying array values:
                        I would have used std::copy. Why reimplement this portion?
                        Again, a simple oversight on my part. I don't work much with arrays, prefering vectors myself (although sometimes it is unavoidable).

                        It directly sets the pointer to 0 (no freeing the memory!).
                        Oddly enough, in the code I have saved locally on my computer, I have 'delete IntArray::iArra y;' in that class member function.

                        Dubious implementation of getArray:
                        The point of your array object is to not have the programmer deal with a raw array. You want to wrap around this array and present a proper interface, not wrap and then give a bunch of set and get functions. You've done nothing but write bloat.
                        I concede this point, but it was faster. Perhaps:
                        Code:
                        int IntArray::getElement(int element)
                        {
                            return IntArray::iArray[element];
                        }
                        would have been better (still not perfect though).

                        Unnecessary setArray:
                        Unneeded because that's what a ctor is for.
                        setArray resizes the array. initArray is more like what you are talking about here. My reason for initArray was to allow a person to create a new null set through the default constructor and later initialize it to a non-null set.

                        Dubious naming of sizeOf.
                        Can be confused with compile time sizeof operator. Not like normal STL containers, which would implement size().
                        This is more of an opinion than a flaw. This could be easily fixed by just naming it numberOfElement s, but that takes alot more typing... and don't suggest numElem. Is that elements? elementary? elementals? I don't like ambiguous abbreviations.

                        Missing critical operators:
                        Like say, the subscript operator?
                        This was not inteded to be a total solution, do not treat it as such. I even stated this before.

                        Use of defines instead of constant ints is C-ish code. You want to create actual constants, which are typesafe and dealt with the compiler, not the pre-compiler.
                        Again, opinion. Defines are just fine. Some people don't like them others do. Some coding format standards for some companies require them others do not. There are good arguments for and against and I will do whatever the person who pays me says since it is irrelevant to doing my job.

                        Code: ( text )
                        IntArray* myFirstArray;
                        IntArray* mySecondArray;
                        Dubious usage. One of the ideas behind a first class type is that the programmer doesn't have to deal with pointers that needs to be managed.
                        I *prefer* pointers to classes.


                        Usage of printf in C++. Why don't you use iostreams? Definitely more typesafe than the variadic printf.
                        Actually, that code is confusing because of cryptic usage of BASE, MULT, TOP, NEW, NEWS(!), and NEWL(!) macros.
                        All of which were written to this companies coding format specification (including the defines).

                        But more to the point, let's look at two examples:
                        Code:
                            iostream << setprecision << 2 << setw << 4 << "    " << myFloat << setprecision << 2 << setw << 4 << myFloat;
                        versus
                        Code:
                            printf("%-4.2f    %-4.2f", myfloat, myfloat);
                        I'll take the second, thank you.


                        Despite it being depricated, it is still in rather common use (<stdio.h> that is).
                        It's in common use because of legacy code. Not because it is OK to keep using stdio.h on fresh codebases.

                        And as for templates, bleh. It makes all the code ugly with all those damned angled brackets and even longer names.
                        I don't believe so, but how is the aesthetic appeal of templates relevant?
                        See above.

                        You save time on the front end by not copying and pasting the code a few times for each type, but then you lose it on the backend having to type all those damn <double>s, <int>s and <whathaveyou> s on the backend everytime you use it your template.
                        You save a lot more when you use generics. Copy pasting code is bad because you exponentially increase maintainability . It increases the work you have to do. It bloats your codebase, because you have repeated yourself. Why are you, a programmer, doing repetitive work, when the computer should be doing it?
                        As I stated before, if I were to really spend time developing this idea, I would first start by creating a Number class that was inherited by Integer, Float, Double, et cetera classes. I would then create an NumberArray Class that would be inherited by the IntegerArray, FloatArray, et cetera classes. I would then put the primary (read as repeating functionality) in the top level class (NumberArray). While this requires a little more code on the front end, it is not a significant amount. This also comes with the advantage that an IntegerArray could be quickly and easily turned into a LongArray using Polymorphism. But this, again, is a preference. I don't work with arrays enough to warrant that because we use vectors unless completely unavoiable here at The City.

                        Plus, in regards to templates, a float and int are not always going to have the same member functions, so it would probably, in all honesty, be best to impliment it as a inherited heirarchy
                        Yet, the concept of an array is independent of the type. You don't want them to be coupled, providing interfaces instead for various operations. Besides, templates give you enormous flexibility in that you can have multiple orthogonal object policies resolved at compile time. Read Alexandrescu's "Modern C++" to see how he handles templates.
                        I know how to handle templates. They are actually quite useful in some circumstances, but I do beleive they are entirely overused. And no amount of argueing will convince me that aren't ugly in the context of C++. Angled brackets belong in HTML, not C++.

                        In your code, you suggest replacing all instances of int with float to get an array type that works with float. Does that not suggest that the member functions for this array type are independent of the type? Furthermore, creating object hierarchies is bad for two major reasons. The first is that you automatically introduce performance penalties unnecessarily. Hierarchies need to be resolved at runtime. Furthermore, it requires coupling. Everytime you want an array of a new type, you repeat code, inherit from some common base, and so on. You created a bloated object hierarchy, all of which involve repeated code. Does this sound appealing to you?
                        A little bloat on the backend versus a little on the front end. Doesn't sound much different to me.

                        I could take 5 seconds to say "The Earth is flat." I could also take 1 year to form that statement. Regardless of how long, my statement is wrong. That you took under 5 minutes to write up the code is irrelevant. It's broken and unusable. If you don't want to be criticized for bad code, and don't want to come off as a bad coder, take the time to write proper code. This is a technical forum, and technical accuracy is valued.
                        I believe I've responded to all your assertations. Take it for what you will.

                        As for the analogy, I could say that it takes the same amount of time to say the Earth is round (5 seconds). However, to really be able to prove that would take alot of work on someones part. So we resolve to saying that the "Earth is Round" all the time, despite the fact that it is technically wrong. It is 'good enough' to say it. But in reality, roundness is a 2-dimentional quality. The Earth is actually spherical. Even that, though, is only technically 'good enough' to get the point accross. To really state such would require to say that the Earth is an 3-dimentional Ellipsoid with an irregular surface. When I'm talking to someone, though, I'd rather just say the Earth is round, and they will know what I mean.

                        Here I threw something together really quickly to illustrate a point. It wasn't intended to be perfect or complete, but it is far better than you give it credit for. I've already acknowledged where I think there are actual flaws. Take it or leave it.

                        Each person has their coding preference. Mine is against templates.
                        One does not have preferences in programming like one prefers colors, or ice cream. A programmer needs to make choices based on technical reasons. Quote:
                        Originally Posted by
                        They are, to say the least, ugly and make the code far more difficult to read. There are many paths to produce the same result.
                        There must be many paths to produce the same result. Because you have a generic container (multiple of one type) applied to infinitely many types. Your idea has programmers manually copying code (and thus code paths) for each type. Using a template has the computer do it. Is not your idea uglier, more difficult to read, far more difficult to maintain?
                        Not even remotely, provided you understand what I said earlier about an object heirarchy. Personally I've been toying with the idea of creating type wrapper classes for C++ for a while and this would just be an extention. I prefer working with objects in total to basic data types (and yes I understand that they will still be basic data types on the backend, but so are all objects, and I prefer working with the objects directly and data types indirectly).

                        My job description...
                        Is irrelevant. Obviously, the reputation and knowledge of people carries weight in the argument. But it does not make it correct. Furthermore, do not expect that in a technical discussion, you will be shielded by reputation, past work, or titles.
                        This was in reference to the attitude you took originally. It is indeed irrelevant to whether the code is good, but as stated above, I believe I've addressed all your concerns and that you were far overreacting to much opinion and a few actual minor flaws.

                        Not only is it in wide use, but C++, by design, retains all of C in its specification.
                        No. C++ is not C. it is not C with a few things tacked on. It is a different language, that implements a subset of C. Therefore, there is very good compatibility with C code. However, it is not complete, and furthermore, idiomatic C code and C++ code differ. If you program C code with a C++ compiler, that's up to you. But it's not idiomatic C++.
                        Correct. C++ is indeed not C. It is C with classes:-p

                        I concede I shouldn't have used <stdio.h>. I also concede this code is not perfect. However, it is workable and gives an idea of what could be done to the questioner. I also think you like generics a bit too much. Most of your issue with my code was that I didn't use a generic class. Just remember, a tool for every job and a job for every tool. This didn't require it nor justify it.

                        I do appreciate you taking the time to actually make your points. The initial attitude was abbrasive to say the least, but these two posts were much better at addressing the actual issues you had and not attacking the person.

                        Comment

                        • developing
                          New Member
                          • Mar 2007
                          • 110

                          #27
                          why don't you do

                          Code:
                          sizeof(array) / sizeof (arrayType)

                          Comment

                          • arnaudk
                            Contributor
                            • Sep 2007
                            • 425

                            #28
                            Originally posted by developing
                            why don't you do
                            Code:
                            sizeof(array) / sizeof (arrayType)
                            sizeof (arrayType) will give the size of a pointer which is 4 bytes on a 32bit machine or 8 on a 64bit machine, regardless of what type the array contains.

                            Comment

                            • Nepomuk
                              Recognized Expert Specialist
                              • Aug 2007
                              • 3111

                              #29
                              Originally posted by developing
                              why don't you do

                              Code:
                              sizeof(array) / sizeof (arrayType)
                              In the original question, I explain, that this doesn't work and I'm looking for an alternative. arnaudk explained the reason. But thank you for trying to help.

                              Greetings,
                              Nepomuk

                              Comment

                              Working...