Personal computing discussed

Moderators: renee, SecretSquirrel, just brew it!

 
Crayon Shin Chan
Minister of Gerbil Affairs
Topic Author
Posts: 2313
Joined: Fri Sep 06, 2002 11:14 am
Location: Malaysia
Contact:

Can't allocate array of arbitrary size

Sat Aug 06, 2011 3:33 pm

Here's some code which VS2003 doesn't like. Basically it finds out how many white pixels are in the image, and then it makes an array the size of the number of white pixels in the image, and then it fills the array with the positions of said white pixels. All in all, very simple, but VS2003 says Error C2057. Why can't the stupid thing just dynamically size the array depending on how many white pixels there are? Must I guess how many white pixels are in the image and provide a concrete number, wasting memory in the process?
   int counter=0;
   int increment=0;
   QRgb currentcolor;
   for(int i=0;i<width;i++)
   {
      for(int j=0;j<height;j++)
      {
         if(qGreen(currentcolor)==g && qRed(currentcolor)==r && qBlue(currentcolor)==b)
         {
            counter++;
         }
      }
   }
   static int whites[2][counter];
   for(int i=0;i<width;i++)
   {
      for(int j=0;j<height;j++)
      {
         if(qGreen(currentcolor)==g && qRed(currentcolor)==r && qBlue(currentcolor)==b)
         {
            whites[0][increment]=i;
            whites[1][increment]=j;
            increment++;
         }
      }
   }
Mothership: FX-8350, 12GB DDR3, M5A99X EVO, MSI GTX 1070 Sea Hawk, Crucial MX500 500GB
Supply ship: [email protected], 12GB DDR3, M4A88TD-V EVO/USB3
Corsair: Thinkpad X230
 
Buub
Maximum Gerbil
Posts: 4969
Joined: Sat Nov 09, 2002 11:59 pm
Location: Seattle, WA
Contact:

Re: Can't allocate array of arbitrary size

Sat Aug 06, 2011 4:12 pm

Arrays are defined at compile time, so the array dimensions need to be something constant that can be determined at compile time.

If you need something dynamic, you want to use std::vector or std::list.

http://msdn.microsoft.com/en-us/library ... 71%29.aspx
 
Zoomastigophora
Gerbil Elite
Posts: 667
Joined: Tue Nov 11, 2008 7:10 pm

Re: Can't allocate array of arbitrary size

Sat Aug 06, 2011 4:18 pm

Or...you could just dynamically allocate it using new.
 
Buub
Maximum Gerbil
Posts: 4969
Joined: Sat Nov 09, 2002 11:59 pm
Location: Seattle, WA
Contact:

Re: Can't allocate array of arbitrary size

Sat Aug 06, 2011 4:35 pm

Zoomastigophora wrote:
Or...you could just dynamically allocate it using new.

... and then forget to free it later...

Far better to get in the habit of using smart containers from the beginning than to handle raw pointers to anonymous bundles of data.

That said, yes you could dynamically allocate it with new (C++) or malloc (if using only C). However if you're using C++, a vector is the right solution for a dynamically allocatable/sizable array.
 
Zoomastigophora
Gerbil Elite
Posts: 667
Joined: Tue Nov 11, 2008 7:10 pm

Re: Can't allocate array of arbitrary size

Sat Aug 06, 2011 6:00 pm

Buub wrote:
Zoomastigophora wrote:
Or...you could just dynamically allocate it using new.

... and then forget to free it later...

Far better to get in the habit of using smart containers from the beginning than to handle raw pointers to anonymous bundles of data.

I'm generally of the opinion that if you're using C/C++ and you don't know the difference between statically, dynamically, and automatically allocated memory, better to learn it early and painfully than to try to debug it later down the road when your code has gotten more complex. I also tend to favor the old school thought of "pay for what you need," and if you don't need the power of STL containers then there's no reason to use them. That said, that's only when dealing with C/C++. For languages like Java or C#, it's much more effective and efficient to use the language library.

<rant>
As an aside, I also dislike "smart" anything when it comes to programming. They tend to hide what it is that they're actually doing, which means the stuff is literally magic to novices trying to learn what's happening, and it's easy to slip into a dependence on them and try to shoehorn their usage in when it's inappropriate. Programmers are universally bad at assuming that they know what users want, but even more so when they think they know what other programmers will want a la "smart" containers or pointers. That's not to say that I discourage their usage, but I'm more tempered in their recommendation with the usual adage of "think about what it is you're trying to do and then pick the right tool for the job." Of course, when I'm dealing with C/C++ code, it's usually game engine related, so I'm probably skewed towards a more performance oriented view.
</rant>
 
Buub
Maximum Gerbil
Posts: 4969
Joined: Sat Nov 09, 2002 11:59 pm
Location: Seattle, WA
Contact:

Re: Can't allocate array of arbitrary size

Sat Aug 06, 2011 8:00 pm

I agree that programmers should know the difference. But I don't let them abdicate their responsibility when you get there -- they should also know how to use the tools to manage that stuff for them.

You're not paying for anything. "STL containers" have been an integral part of every compliant C++ compiler since the 1998 standard. I disagree with the "no need to use them" philosophy, in preference to the "why wouldn't you use them" when they're a standard part of the language library -- they are a defacto part of the compiler's tool set.

Try to think of this modern C++ paradigm as an entirely different language rather than a super-charged version of C.

And the cost is also minimal in the compiled code. STL containers specifically, and templatized code in general, typically compile down quite efficiently with modern compilers. The runtime performance is quite good as well, because this is templatized code and not a bunch of runtime magic.

I agree with you that none of this stuff should be magic, and that the programmer should understand how it works and how the memory usage is handled underneath the covers. That said, RAII is one of the most powerful paradigms in modern C++ programming. Embracing it more widely would result in much higher quality programs with fewer lines of code.


... but... I understand where you're coming from. Using C code for very tight engine code is an understandable choice for the same reason as using assembly to make platform-specific high performance string functions. My point of view is from a more general application development perspective. But don't make the mistake that C++ can't be performant enough in many situations. I have friends who do embedded development, and even they are starting to move to C++ because they simply can't deny the benefits of some of these higher level paradigms any longer, and the size and performance cost of using C++ are not significantly worse that C any longer in many cases.
 
morphine
TR Staff
Posts: 11600
Joined: Fri Dec 27, 2002 8:51 pm
Location: Portugal (that's next to Spain)

Re: Can't allocate array of arbitrary size

Sat Aug 06, 2011 8:34 pm

Also, Crayon, what is the end-purpose of this? Homework/assignment? Is it something that needs to be fast and is part of a real-time engine, or just a batch process or something similar? If it's the latter, you can also consider one of the many scripting languages, which make this kind of task much easier.
There is a fixed amount of intelligence on the planet, and the population keeps growing :(
 
Zoomastigophora
Gerbil Elite
Posts: 667
Joined: Tue Nov 11, 2008 7:10 pm

Re: Can't allocate array of arbitrary size

Sat Aug 06, 2011 10:10 pm

Buub wrote:
You're not paying for anything. "STL containers" have been an integral part of every compliant C++ compiler since the 1998 standard. I disagree with the "no need to use them" philosophy, in preference to the "why wouldn't you use them" when they're a standard part of the language library -- they are a defacto part of the compiler's tool set.

Well it's not so much as "no need to use them" as "be sure you should be using them when you do." As with all things in programming, there are no laws that can be universally applied to all situations - it's the programmer's responsibility to evaluate what his needs and requirements are and then produce an appropriate solution. I get nervous when I see people use the phrase you did: "why wouldn't you use them;" I take that question quite seriously :). That being said, more often than not, you will want to use an STL container for their convenience and robustness and it certainly reduces some of the more subtle issues of arrays.

Buub wrote:
That said, RAII is one of the most powerful paradigms in modern C++ programming. Embracing it more widely would result in much higher quality programs with fewer lines of code.

It's funny you should mention RAII. I ran across this subtle smart-pointer gotcha a while back, and it was a total pain to track down. RAII is certainly powerful and I would recommend its usage in the general case if you're the one implementing the pattern, but be aware of any library/platform specific weirdness if you're using someone else's RAII designs :P

Buub wrote:
My point of view is from a more general application development perspective. But don't make the mistake that C++ can't be performant enough in many situations. I have friends who do embedded development, and even they are starting to move to C++ because they simply can't deny the benefits of some of these higher level paradigms any longer, and the size and performance cost of using C++ are not significantly worse that C any longer in many cases.

I agree and I use C++ in most situations. I actually started my programming off in Java so I'm pretty inclined to use libraries whenever it's reasonable to do so, so I can spend time focusing on the actual problem being solved rather than micromanaging memory allocation details and whatnot, but I thought I'd provide a counter-balance to your advice for the sake of completeness :D.
 
Buub
Maximum Gerbil
Posts: 4969
Joined: Sat Nov 09, 2002 11:59 pm
Location: Seattle, WA
Contact:

Re: Can't allocate array of arbitrary size

Sun Aug 07, 2011 12:16 am

Ah yes, I would definitely have put the CoUnitialize in a scope outside anything that uses it, for that very reason. But I can see how that would be hard to catch if the code had already been written.

Anyway, back to the original question:
IMHO, std::vector is the correct solution for a dynamic array problem in C++.

If you are using C, or you simply don't want to go with the container classes, then malloc or new of a batch of memory, and managing it explicitly, would be the necessary solution.
 
seeker010
Gerbil First Class
Posts: 143
Joined: Sat Oct 19, 2002 8:52 am

Re: Can't allocate array of arbitrary size

Sun Aug 07, 2011 2:54 am

Buub wrote:
If you are using C, or you simply don't want to go with the container classes, then malloc or new of a batch of memory, and managing it explicitly, would be the necessary solution.

dynamic arrays are part of the C99 standard, IIRC
 
Zoomastigophora
Gerbil Elite
Posts: 667
Joined: Tue Nov 11, 2008 7:10 pm

Re: Can't allocate array of arbitrary size

Sun Aug 07, 2011 3:44 am

seeker010 wrote:
dynamic arrays are part of the C99 standard, IIRC

Not dynamic arrays, variable length arrays. You would have to compile in C mode as well because C++ doesn't support VLAs. If Crayon can use just C and needs the array only within a particular scope, he could potentially get away with using VLAs, but I don't recommend it. I would favor std::vector over using VLAs.
 
Crayon Shin Chan
Minister of Gerbil Affairs
Topic Author
Posts: 2313
Joined: Fri Sep 06, 2002 11:14 am
Location: Malaysia
Contact:

Re: Can't allocate array of arbitrary size

Sun Aug 07, 2011 3:48 am

This is a project for some paper my professor's working on. I'm trying to control a human to trace a shape defined by an image, where the shape is described by a white line. Currently, the algorithm is very simple and forces you to go over each pixel, i.e. no shortcuts allowed. A 2 pixel wide line is not allowed, because if it were allowed then it would force you to go down it, up and down again because that's just the way the 2D vector is filled up.

Yes, I'm using vectors now. I really hate how the syntax is so haphazard. It's the main reason I never use most of the features of C++ and stick to plain old C style programming. "new" hardly implies anything dynamic to me, and <vector vector<int> > really irks me.
Mothership: FX-8350, 12GB DDR3, M5A99X EVO, MSI GTX 1070 Sea Hawk, Crucial MX500 500GB
Supply ship: [email protected], 12GB DDR3, M4A88TD-V EVO/USB3
Corsair: Thinkpad X230
 
Buub
Maximum Gerbil
Posts: 4969
Joined: Sat Nov 09, 2002 11:59 pm
Location: Seattle, WA
Contact:

Re: Can't allocate array of arbitrary size

Sun Aug 07, 2011 1:31 pm

The syntax is logical once you get used to it. It's bizarre simply because of the design evolution of C/C++. You have to make it work in the syntactical way the languages work. If you keep that in mind, it makes sense. If you want to see bizarre, look at the advanced regular expression language developed for the boost regular expression library!

If you don't like the verboseness, you could try some typedefs:

typedef vector<int> intVector_t;
typedef vector<intVector_t> intIntVector_t;

...

for (intVector_t::interator it = someVec.begin(); it != someVec.end(); ++it)
{
... some stuff
}

etc...
 
Zoomastigophora
Gerbil Elite
Posts: 667
Joined: Tue Nov 11, 2008 7:10 pm

Re: Can't allocate array of arbitrary size

Sun Aug 07, 2011 2:43 pm

I'm not a huge fan of nesting STL containers either for the same reason: the syntax to do anything becomes really ugly really quickly. Typedefing just hides the ugliness and obfuscates what's happening to anyone reading the code. In your particular case though, I don't think you actually need a nested vector. Use a simple struct to store (x,y) coordinates of white pixels, then you can just have a vector<Position> and things become much less messy.

Tangentially, refusing to learn or use features of a language because the syntax doesn't match what you know is kind of absurd. Every programming language's syntax is arbitrary, it's just the nature of the beast. For instance, the "malloc" keyword from C isn't much better than "new." To newcomers, malloc doesn't naturally map to any known concept and it's not immediately obviously that's it's a portmanteau of "memory allocate." Even if you did know what the keyword stood for, "memory allocate" doesn't tell you much more either; is it allocating memory on the heap or the stack? Maybe it's reserving a portion of memory that was already assigned to the program when it started up. Point is, when dealing with any language, you will have to map arbitrary keywords to a specific behavior.

Who is online

Users browsing this forum: No registered users and 1 guest
GZIP: On