Bool pointer to an array help C++

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

HappySmileMan
Posts: 52
Joined: Fri Nov 09, 2007 11:46 pm UTC

Bool pointer to an array help C++

Postby HappySmileMan » Sat Jan 12, 2008 12:22 am UTC

I'm in C++ and I'm trying to do this:

Code: Select all

bool **active, **inactive, **temp;
active = new bool[8][8];
inactive = new bool[8][8];


But I get the errors
/home/paul/GoL/src/gol.cpp:47: error: cannot convert 'bool (*)[8]' to 'bool**' in assignment
/home/paul/GoL/src/gol.cpp:48: error: cannot convert 'bool (*)[8]' to 'bool**' in assignment


I've also tried "bool *active[]" to declare it. With similar messages, how can this be done?

These are the first lines of my main() function so nothing up to then could be causing the error, adn no global variables either

Edit: Should this be moved to the It doesn't work thread? If so someone with the power to do that can do it. I forgot about that thread

!xobile
Posts: 26
Joined: Sat Aug 25, 2007 3:04 am UTC
Location: Colorado

Re: Bool pointer to an array help C++

Postby !xobile » Sat Jan 12, 2008 1:50 am UTC

I don't think you need to have the bool* you just need bool active[8][8].

HappySmileMan
Posts: 52
Joined: Fri Nov 09, 2007 11:46 pm UTC

Re: Bool pointer to an array help C++

Postby HappySmileMan » Sat Jan 12, 2008 1:53 am UTC

!xobile wrote:I don't think you need to have the bool* you just need bool active[8][8].


Needed to be able to swap around what active and inactive referred to, using the temp pointer for swapping, I think that makes sense anyway.

I got it working anyway... Turning out I was googling for "pointer to multi-dimensional cool array" by accident :P

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: Bool pointer to an array help C++

Postby Sc4Freak » Sat Jan 12, 2008 3:31 am UTC

Since you're using C++, you may want to consider using boost::multi_array. If you need to swap these things around by pointer, then this would be much cleaner:

Code: Select all

typedef boost::multi_array<bool, 2> Bool2DArray;
boost::shared_ptr< Bool2DArray > active(new Bool2DArray(boost::extents[8][8]));
boost::shared_ptr< Bool2DArray > inactive(new Bool2DArray(boost::extents[8][8]));

// To swap the pointers, use std::swap(). No need to reinvent the wheel.
std::swap(active, inactive);


Since that's using smart pointers, the arrays will automatically be cleaned up (deleted) when it's no longer used, guaranteeing that no memory leaks will occur. The usage of std::swap means that you don't need the "temp" var. And the usage of boost::multi_array means that you don't need to deal with raw arrays (which as you found out are brittle, hard to use, and evil).

User avatar
taby
Posts: 154
Joined: Thu Nov 01, 2007 8:39 pm UTC
Location: Canada

Re: Bool pointer to an array help C++

Postby taby » Sat Jan 12, 2008 6:55 pm UTC

One other way to go is STL, which is an official part of C++ itself, so it should work with any modern compiler automatically.

#include <vector>
using std::vector;

...

vector<bool> lala(8*8);

lala[0] = false;

The vector automatically frees this memory when it goes out of scope, so no manual calls to new[]/delete[] are required.

The other thing about vector<bool> is that it's specialized to use one bit of memory per bool. If you were to use the array method, ex: bool lala[8*8]; then each of those would most likely take up one byte. When you deal with vectors/arrays of millions of bools, the difference of 7 bits per bool really adds up fast.

Goplat
Posts: 490
Joined: Sun Mar 04, 2007 11:41 pm UTC

Re: Bool pointer to an array help C++

Postby Goplat » Sat Jan 12, 2008 7:57 pm UTC

C++ libraries: Making simple tasks complicated since 1994.

Sc4Freak wrote:Since you're using C++, you may want to consider using boost::multi_array. If you need to swap these things around by pointer, then this would be much cleaner:

Code: Select all

typedef boost::multi_array<bool, 2> Bool2DArray;
boost::shared_ptr< Bool2DArray > active(new Bool2DArray(boost::extents[8][8]));
boost::shared_ptr< Bool2DArray > inactive(new Bool2DArray(boost::extents[8][8]));
That's "cleaner"?!
std::swap(active, inactive);
You could do that even if active and inactive were ordinary pointers.

Without seeing the rest of the code we don't know what the lifetime of these two arrays is supposed to be. Probably they last throughout the main() function, so reference counting would be overkill, like it is in most cases.

If they are just supposed to last until the function returns, dynamic allocation isn't even needed at all:

Code: Select all

bool arrays[2][8][8];
bool (*active)[8] = arrays[0];
bool (*inactive)[8] = arrays[1];
It doesn't get any simpler than that.
And the usage of boost::multi_array means that you don't need to deal with raw arrays (which as you found out are brittle, hard to use, and evil).
Sure they're "brittle" in the sense that they're of fixed sizes. But often a fixed size array is all that's needed, as it apparently is in this case. As for your other two "criticisms", please put forth some actual justification for them.

As for taby's suggestion: Sure you save 56 bytes of data that way, but that will probably be dwarfed by all the std::vector code that will get added. If you want to save memory just use unsigned char[8] instead of bool[8][8]. Accessing the bits is a tad unwieldy ("active[y] >> x & 1") but using the vector wouldn't be nice either because it must be used one-dimensionally ("active[y * 8 + x]").

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Bool pointer to an array help C++

Postby EvanED » Sat Jan 12, 2008 8:50 pm UTC

taby wrote:One other way to go is STL, which is an official part of C++ itself, so it should work with any modern compiler automatically.

#include <vector>
using std::vector;

...

vector<bool> lala(8*8);

lala[0] = false;

The vector automatically frees this memory when it goes out of scope, so no manual calls to new[]/delete[] are required.

The other thing about vector<bool> is that it's specialized to use one bit of memory per bool. If you were to use the array method, ex: bool lala[8*8]; then each of those would most likely take up one byte. When you deal with vectors/arrays of millions of bools, the difference of 7 bits per bool really adds up fast.

Unless you have reason to use vector (e.g. the guarantee that everything is layout-compatible with a C array), I and others suggest using a std::deque of bools rather than a vector of bools.

vector<bool> is... strange, and has some problems.

HappySmileMan
Posts: 52
Joined: Fri Nov 09, 2007 11:46 pm UTC

Re: Bool pointer to an array help C++

Postby HappySmileMan » Sun Jan 13, 2008 12:17 am UTC

The program was like a 70 line implementation of "Conway's game of life" because I was bored and saw it while here. I'm pretty sure a multi-dimensional array of bools is fine for this. Though std::swap() is interesting.

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: Bool pointer to an array help C++

Postby Sc4Freak » Sun Jan 13, 2008 2:17 am UTC

Goplat wrote:C++ libraries: Making simple tasks complicated since 1994.

Sc4Freak wrote:Since you're using C++, you may want to consider using boost::multi_array. If you need to swap these things around by pointer, then this would be much cleaner:

Code: Select all

typedef boost::multi_array<bool, 2> Bool2DArray;
boost::shared_ptr< Bool2DArray > active(new Bool2DArray(boost::extents[8][8]));
boost::shared_ptr< Bool2DArray > inactive(new Bool2DArray(boost::extents[8][8]));
That's "cleaner"?!
std::swap(active, inactive);
You could do that even if active and inactive were ordinary pointers.

Without seeing the rest of the code we don't know what the lifetime of these two arrays is supposed to be. Probably they last throughout the main() function, so reference counting would be overkill, like it is in most cases.

If they are just supposed to last until the function returns, dynamic allocation isn't even needed at all:

Code: Select all

bool arrays[2][8][8];
bool (*active)[8] = arrays[0];
bool (*inactive)[8] = arrays[1];
It doesn't get any simpler than that.
And the usage of boost::multi_array means that you don't need to deal with raw arrays (which as you found out are brittle, hard to use, and evil).
Sure they're "brittle" in the sense that they're of fixed sizes. But often a fixed size array is all that's needed, as it apparently is in this case. As for your other two "criticisms", please put forth some actual justification for them.

As for taby's suggestion: Sure you save 56 bytes of data that way, but that will probably be dwarfed by all the std::vector code that will get added. If you want to save memory just use unsigned char[8] instead of bool[8][8]. Accessing the bits is a tad unwieldy ("active[y] >> x & 1") but using the vector wouldn't be nice either because it must be used one-dimensionally ("active[y * 8 + x]").

It's cleaner in the sense that it's easier to manage, maintain, debug, and use. The code may be more ugly/verbose, but the extra few characters used are well worth the added security.

I tend to avoid using raw arrays like that. Static, fixed-size arrays can be fine; they have their uses. But when it comes to dynamically-allocated arrays, there's no reason to use raw pointers with new[]/delete[]. The STL is there for a reason, it's there to increase code safety and decrease code problems and bugs. Unfortunately, the STL doesn't provide by default a multi-dimensional container with familiar syntax, so that's where the boost libraries come in. multi_array is a very quick and easy way to create dynamically sized rectangular multi-dimensional arrays.

Pointers are notoriously difficult to manage. In any large project, you've no doubt discovered that raw pointers can suffer from ownership issues: who owns the data pointed to by the pointer? And who should destroy it? If you forget to delete something, you get a memory leak. If you delete it when you shouldn't have, you crash your program. Smart pointers guarantee (within reason) that the memory will be correctly released when nobody needs it anymore, and no sooner. I don't see how increasing code safety and reliability could ever be viewed as a bad thing.

Although it hasn't been mentioned yet, if there's anyone looking to criticise the potential performance implications of the STL over C-style constructs, I need to point out that micro optimisations are stupid. Premature optimisation is the root of all evil, as the old saying goes. Smart pointers and multi_array may be slower than their C-style counterparts, but I would gladly trade 10% of my performance for the guarantees of safety and the ease-of-use of these classes.

Arrays are hard to use because often they're unintuitive and not straight forward enough. The OP's post is an example of this. Take this as another example:

Code: Select all

char* str1 = "abc";
str1[0] = '1';

At a cursory glance, it seems OK. But it'll crash your program. Someone who didn't know about this particular bug could potentially spend hours trying to find the problem. But if a string was used instead, no problems like this would ever occur.

Code: Select all

std::string str1 = "abc";
str1[0] = '1'; // ok


Another common mistake is this:

Code: Select all

int* array = new int[100];
int* arraycopy = array;
delete [] array;
arraycopy[0] = 1;

That'll crash your program, because assignment doesn't actually copy the contents of the array, unintuitively. This would be better:

Code: Select all

std::vector<int> arraycopy
{
    std::vector<int> array(100);
    arraycopy = array;
}
arraycopy[0] = 1;

No nasty pointers, no manual memory management, and usage of scope to manage object lifetimes.

There are countless other examples as to why raw pointers can cause problems. I'm sure that you could think of some others on your own.

If you want to use C, go use C. And go deal with your raw pointers, arrays, and malloc/free. If you're using C++, it's silly to adhere to old potentially unsafe C-style constructs for no apparent reason when there are clear (and better) alternatives.

User avatar
taby
Posts: 154
Joined: Thu Nov 01, 2007 8:39 pm UTC
Location: Canada

Re: Bool pointer to an array help C++

Postby taby » Sun Jan 13, 2008 3:11 am UTC

EvanED wrote:vector<bool> is... strange, and has some problems.


Can you elaborate?

I've used std::vector<bool> many times, without issue (ex: they work like a vector should, from my experience). In fact, my fractal app relies on them for about a dozen different things (http://cpp.criticaldamage.com/index.php ... creenshots).
Last edited by Hammer on Sun Jan 13, 2008 3:15 am UTC, edited 1 time in total.
Reason: Fixed quote tags

User avatar
Hangar
Posts: 171
Joined: Fri Nov 23, 2007 3:41 am UTC

Re: Bool pointer to an array help C++

Postby Hangar » Sun Jan 13, 2008 3:54 am UTC

It's specialized to only take one bit per member, so it can't be addressed correctly and doesn't work like a vector in other ways. It's only a huge problem when making generic algorithms, but most people stay away from it.

hic erro
Posts: 7
Joined: Sat Nov 17, 2007 5:51 pm UTC
Location: Astoria, NY

Re: Bool pointer to an array help C++

Postby hic erro » Sun Jan 13, 2008 4:22 am UTC

Hangar wrote:It's specialized to only take one bit per member, so it can't be addressed correctly and doesn't work like a vector in other ways. It's only a huge problem when making generic algorithms, but most people stay away from it.

Which problems are you referring to specifically?

Most of the quirks fall away when you go even further into the STL; for instance, op[] doesn't return a bool&, which might be annoying, but it returns a vector<bool>::reference, so if you STL-ify your generic algorithms even more and say "vector<T>::reference" instead of "T&", that little problem becomes a non-problem.

Goplat
Posts: 490
Joined: Sun Mar 04, 2007 11:41 pm UTC

Re: Bool pointer to an array help C++

Postby Goplat » Sun Jan 13, 2008 4:23 am UTC

Yeah, I've hard all this stuff before about how hard to use pointers supposedly are, and I don't buy it.
Arrays are hard to use because often they're unintuitive and not straight forward enough. The OP's post is an example of this. Take this as another example:

Code: Select all

char* str1 = "abc";
str1[0] = '1';
This has nothing to do with arrays in general. This is about quoted string constants, which are read-only but are still allowed to be used as ordinary char* because people would have to add tons of "const"s into their old code if this was ever changed. It's only quoted strings that have this discrepancy. In other situations, you can't make the mistake. Try this:

Code: Select all

extern const char* func();
char* str = func();
You'll get at least a warning, probably even an error.
Someone who didn't know about this particular bug could potentially spend hours trying to find the problem. But if a string was used instead, no problems like this would ever occur.
If you don't know the language you're using, you're going to make mistakes no matter what. Maybe you could use std::string but try to write to characters past the end, thinking that it will expand automatically. Oops, you just screwed up the heap, but the bug doesn't manifest until the next allocation, which happens in completely unrelated code. A bug like that would be a huge pain to track down (a lot worse than writing to a constant, which triggers a CPU exception immediately - with a debugger, finding that bug would take seconds).
Another common mistake is this: int* arraycopy = array;
The only way someone could think that that makes a copy is if they don't know what a pointer is yet.
because assignment doesn't actually copy the contents of the array, unintuitively.
And assigning a shared_ptr does copy the array? Sorry, but people need to learn that two pointers can reference the same thing, and nothing short of going back to the GW-BASIC memory model - abolishing dynamic allocation entirely - can change that. Even if deletion is irrelevant, there's also the simple fact that changes made through one pointer will be visible through the other.

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: Bool pointer to an array help C++

Postby Sc4Freak » Sun Jan 13, 2008 4:44 am UTC

Goplat wrote:Yeah, I've hard all this stuff before about how hard to use pointers supposedly are, and I don't buy it.

It depends on whether you've had to deal with these problems before or not. I've personally had nightmarish debugging scenarios involving dangling pointers, double-deletion, uninitialised memory, memory leaks, etc. After that experience, I now try to use the STL as opposed to manual C-style arrays, and I try not to use pointers unless I have to. And even then, I try to use a smart pointer. I've had a lot less problems since then. An added side effect is that coding is made easier once you familiarise yourself with the STL - I'm no longer constantly reinventing the wheel. Previously, I had never realised how useful <algorithm> was. But I digress.

If you don't know the language you're using, you're going to make mistakes no matter what. Maybe you could use std::string but try to write to characters past the end, thinking that it will expand automatically. Oops, you just screwed up the heap, but the bug doesn't manifest until the next allocation, which happens in completely unrelated code. A bug like that would be a huge pain to track down (a lot worse than writing to a constant, which triggers a CPU exception immediately - with a debugger, finding that bug would take seconds).

That's some dubious reasoning. You can walk off the end of a C-style array just the same as a std::string. Both are errors, and both are bugs with unexpected behaviour. You can't seriously be saying that C-style arrays are better because they can be just as bad as std::string. Besides, in any semi-recent implementation, an attempt to access an element out of bounds of a STL container or a std::string will result in a run-time assert. You won't get that in any C-style array when attempting to overwrite the bounds of the array. In fact, the usage of C-style arrays is why buffer overruns were such a problem (and why the updated Microsoft CRT includes "safe" C functions which performs the same out-of-bounds checking, which you automatically get with the STL).

The only way someone could think that that makes a copy is if they don't know what a pointer is yet.

Doesn't matter. It's unintuitive.

And assigning a shared_ptr does copy the array? Sorry, but people need to learn that two pointers can reference the same thing, and nothing short of going back to the GW-BASIC memory model - abolishing dynamic allocation entirely - can change that. Even if deletion is irrelevant, there's also the simple fact that changes made through one pointer will be visible through the other.

A key point here is that a pointer is not an array. An array can degenerate into a pointer, but it is not an array nonetheless. A shared_ptr is is NOT an array. A shared_ptr is just that - a pointer. Assignment of a pointer, expectedly, does not copy the pointed-to data. std::vector might be considered like an array, and it acts like one. Copy the array, and expectedly the contents are also copied.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Bool pointer to an array help C++

Postby EvanED » Sun Jan 13, 2008 10:22 am UTC

taby wrote:
EvanED wrote:vector<bool> is... strange, and has some problems.


Can you elaborate?

I've used std::vector<bool> many times, without issue (ex: they work like a vector should, from my experience). In fact, my fractal app relies on them for about a dozen different things (http://cpp.criticaldamage.com/index.php ... creenshots).

vector<bool> does not meet all of the conditions required to be a true STL container, because the standards committee decided to provide a specialization for bool that behaves differently. For instance, operator[] does not return a (const) bool &, only something that behaves almost like it.

The suggestion to avoid vector<bool> is only because it can break in some really weird places. You're not likely to encounter them, but if you do and aren't thinking about the fact that "vector<bool>" is different from "vector<T> with T = bool", they can be hard to diagnose.

At any rate, it's not a terribly dire warning or anything, and probably somewhat of a style preference. There are even some reasons you may prefer it; it'll probably take up 1/8th the memory of a deque<bool> (at the cost of somewhat slower accesses). However, it seems to me that, if you don't have a reason to prefer vector, take the option that has zero probability of behaving differently from what you'd expect rather than the one that has small probability. And I'm not the only one who thinks this way; I've got at least Scott Meyers on my side.

hic erro wrote:Most of the quirks fall away when you go even further into the STL; for instance, op[] doesn't return a bool&, which might be annoying, but it returns a vector<bool>::reference, so if you STL-ify your generic algorithms even more and say "vector<T>::reference" instead of "T&", that little problem becomes a non-problem.

This is only sometimes possible (okay, maybe it usually is, but still not always), e.g. if you don't need to pass the element to another function that takes a reference.

hic erro
Posts: 7
Joined: Sat Nov 17, 2007 5:51 pm UTC
Location: Astoria, NY

Re: Bool pointer to an array help C++

Postby hic erro » Sun Jan 13, 2008 4:45 pm UTC

EvanED wrote:
hic erro wrote:Most of the quirks fall away when you go even further into the STL; for instance, op[] doesn't return a bool&, which might be annoying, but it returns a vector<bool>::reference, so if you STL-ify your generic algorithms even more and say "vector<T>::reference" instead of "T&", that little problem becomes a non-problem.

This is only sometimes possible (okay, maybe it usually is, but still not always), e.g. if you don't need to pass the element to another function that takes a reference.

More style issues; if you write your generic functions as

Code: Select all

template <typename T>
void foo( T &a, T &b ) {
  // ...
}

of course you'll have problems.

If you write your functions as

Code: Select all

template <typename T>
void foo( T a, T b ) {
  // ...
}

and then let T = int& or vector<bool>::reference, you can get the desired behavior.

It is annoying that you lose the ability to cleanly say "I expect the parameter to be a reference type", but work-arounds to this exist, eg, Boost concept-check. (Although they do not include a 'ReferenceConcept' check, so you'd have to implement your own, and you'd have to implement the specialization which recognized vector<bool>::reference as a concept yourself...)

It also, of course, leaves you high-and-dry if you didn't actually write the function in the first place, but are importing it from a library.

User avatar
taby
Posts: 154
Joined: Thu Nov 01, 2007 8:39 pm UTC
Location: Canada

Re: Bool pointer to an array help C++

Postby taby » Sun Jan 13, 2008 4:59 pm UTC

Thank you all for elaborating. This is very informative. I do like Scott Meyers' work a lot. :)

Hangar -- Iterators were designed to replace direct pointer addressing for STL containers. The only time I will ever use pointer addressing is when I have to use an int* into a C function (or whatever type), and even then I feel guilty. ex: void func(int* param) ... vector<int> x; ... func(&x[0]). The reason I do this is to avoid new[]/delete[] altogether, and vector's elements are designed to be contiguous in memory, but that's only my preference.

Anyway, everyone's responses have been thoroughly professional. Thank you.

User avatar
Hangar
Posts: 171
Joined: Fri Nov 23, 2007 3:41 am UTC

Re: Bool pointer to an array help C++

Postby Hangar » Sun Jan 13, 2008 7:13 pm UTC

No, I realize that, but things like efficiency and consistency fall away because of it in this case.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Bool pointer to an array help C++

Postby EvanED » Sun Jan 13, 2008 9:19 pm UTC

hic erro wrote:If you write your functions as

Code: Select all

template <typename T>
void foo( T a, T b ) {
  // ...
}

and then let T = int& or vector<bool>::reference, you can get the desired behavior.

If you do that, it won't infer T (it would infer int for the first case, not int&); you would have to specify it each time.

Again, there are ways around many of these problems, but if you don't otherwise care, why not just avoid them entirely with deque?

User avatar
segmentation fault
Posts: 1770
Joined: Wed Dec 05, 2007 4:10 pm UTC
Location: Nu Jersey
Contact:

Re: Bool pointer to an array help C++

Postby segmentation fault » Mon Jan 14, 2008 1:25 pm UTC

Code: Select all

bool **active, **inactive, **temp;
active = new bool* [8];
inactive = new bool* [8];
for (int i=0; i < 8; i++)
{
  active[i] = new bool[8];
  inactive[i] = new bool[8];
}


should work.
people are like LDL cholesterol for the internet

Goplat
Posts: 490
Joined: Sun Mar 04, 2007 11:41 pm UTC

Re: Bool pointer to an array help C++

Postby Goplat » Mon Jan 14, 2008 5:25 pm UTC

Eww. This isn't Java; C++ has real multidimensional arrays.

User avatar
segmentation fault
Posts: 1770
Joined: Wed Dec 05, 2007 4:10 pm UTC
Location: Nu Jersey
Contact:

Re: Bool pointer to an array help C++

Postby segmentation fault » Mon Jan 14, 2008 5:47 pm UTC

taby wrote:
EvanED wrote:vector<bool> is... strange, and has some problems.
Can you elaborate?


its due to the fact that bools are only 1 bit. vector<bool>'s elements arent addressable since 8 bools fit into 1 byte.

it basically proves why premature optimization is evil.

oh people have gone in depth about this already :( im on internet mountain time.

Goplat wrote:Eww. This isn't Java; C++ has real multidimensional arrays.


...as opposed to "fake" ones? sorry to say but i have no idea how else to allocate multidimensional arrays dynamically in c++.
people are like LDL cholesterol for the internet

User avatar
yy2bggggs
Posts: 1261
Joined: Tue Oct 17, 2006 6:42 am UTC

Re: Bool pointer to an array help C++

Postby yy2bggggs » Tue Jan 15, 2008 12:00 am UTC

segmentation fault wrote:
Goplat wrote:Eww. This isn't Java; C++ has real multidimensional arrays.

...as opposed to "fake" ones? sorry to say but i have no idea how else to allocate multidimensional arrays dynamically in c++.


Quick and dirty way.

Code: Select all

struct MyArray
{
   typedef bool array_t[8][8];
   array_t _data;
   operator array_t&() {return _data;}
};

// demo
#include <memory>
#include <iostream>
int main()
{
   MyArray x =
   {false,false,false,false,false,false,false,false
   ,false,true,false,false,false,false,false,false
   ,false,false,false,false,false,false,false,false}; // rest are "zero-initialized"

   std::auto_ptr<MyArray> py(new MyArray);
   *py = x;
   std::cout << ( (*py)[1][1] ? "OK" : "BAD" ) << std::endl;
}


Edit: This is just showing how/that it can be done. If you want to use this for anything non-trivial, you may want to add at least operator const array_t&, and other entities according to needs.
Image

User avatar
segmentation fault
Posts: 1770
Joined: Wed Dec 05, 2007 4:10 pm UTC
Location: Nu Jersey
Contact:

Re: Bool pointer to an array help C++

Postby segmentation fault » Tue Jan 15, 2008 1:35 pm UTC

well...thats not dynamic allocation. however, im beginning to wonder if the OP even needs to do it dynamically since we know the size anyway.
people are like LDL cholesterol for the internet

User avatar
yy2bggggs
Posts: 1261
Joined: Tue Oct 17, 2006 6:42 am UTC

Re: Bool pointer to an array help C++

Postby yy2bggggs » Tue Jan 15, 2008 2:24 pm UTC

segmentation fault wrote:well...thats not dynamic allocation. however, im beginning to wonder if the OP even needs to do it dynamically since we know the size anyway.

There's a terminology issue here. What you seem to be referring to is a dynamically sized array. That's just a vector.
Image

User avatar
segmentation fault
Posts: 1770
Joined: Wed Dec 05, 2007 4:10 pm UTC
Location: Nu Jersey
Contact:

Re: Bool pointer to an array help C++

Postby segmentation fault » Tue Jan 15, 2008 3:46 pm UTC

dynamic allocation is allocating memory during run-time as opposed to compile-time. dynamic allocation, in other words, is signified by the use of things like new or malloc, which is what the OP was trying to do, and im beginning to wonder if he/she needs to do it when he/she can just statically allocate it since we know the desired size.
people are like LDL cholesterol for the internet

User avatar
Daemonic
Posts: 32
Joined: Sat Sep 22, 2007 9:40 pm UTC
Location: Waterloo, On
Contact:

Re: Bool pointer to an array help C++

Postby Daemonic » Tue Jan 15, 2008 5:13 pm UTC

segmentation fault wrote:dynamic allocation is allocating memory during run-time as opposed to compile-time. dynamic allocation, in other words, is signified by the use of things like new or malloc, which is what the OP was trying to do, and im beginning to wonder if he/she needs to do it when he/she can just statically allocate it since we know the desired size.

I'd agree. It makes a lot more sense (especially since the arrays aren't that big) to do static allocation in this case. Especially since, from the description of the problem, there doesn't seem to be a need for dynamic allocation; they are declared (from his description) in main().

User avatar
yy2bggggs
Posts: 1261
Joined: Tue Oct 17, 2006 6:42 am UTC

Re: Bool pointer to an array help C++

Postby yy2bggggs » Wed Jan 16, 2008 12:06 am UTC

segmentation fault wrote:dynamic allocation is allocating memory during run-time as opposed to compile-time.

Correct, sort of. std::auto_ptr<MyArray> py points to dynamically allocated memory. (Technically, automatic variables are also allocated at runtime, and even certain variables of static duration are allocated at runtime).
... and im beginning to wonder if he/she needs to do it when he/she can just statically allocate it since we know the desired size.

Certainly, and it's probably what he should actually do as well. He wants to be able to efficiently swap them with pointers, but that's just a matter of making the pointers point to something that is an array of the desired dimensions, and that array doesn't have to be dynamic.

Code: Select all

int main()
{
   typedef bool board_t[8][8];
   board_t board1={};
   board_t board2={};
   board_t *active=&board1;
   board_t *inactive=&board2;
   // ...
}
Image

User avatar
Sc4Freak
Posts: 673
Joined: Thu Jul 12, 2007 4:50 am UTC
Location: Redmond, Washington

Re: Bool pointer to an array help C++

Postby Sc4Freak » Wed Jan 16, 2008 5:58 am UTC

http://xkcd.com/371/

Don't do it, for the sake of your computer! :lol:

User avatar
segmentation fault
Posts: 1770
Joined: Wed Dec 05, 2007 4:10 pm UTC
Location: Nu Jersey
Contact:

Re: Bool pointer to an array help C++

Postby segmentation fault » Wed Jan 16, 2008 6:31 am UTC

yy2bggggs wrote:Correct, sort of. std::auto_ptr<MyArray> py points to dynamically allocated memory.


auto_ptr contains a pointer to allocated memory. the 2 are different.
people are like LDL cholesterol for the internet


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 11 guests