1

So how would I create an array which would contain pointers to other arrays, so that I can still access the arrays that the overall array points to? I tried this:

#include <iostream>

using namespace std;

int main (void)
{

bool (*arrays)[3], *arr1, *arr2, *arr3, *tempArr;

arr1 = new bool[2];
arr2 = new bool[2];
arr3 = new bool[2];

arr1[0] = arr2[0] = arr3[0] = 0;
arr1[1] = arr2[1] = arr3[1] = 1;

arrays[0] = arr1;
arrays[1] = arr2;
arrays[2] = arr3;

int n = 0;

while (n <= 2) {

    tempArr = arrays[n];

    cout << tempArr[0] << tempArr[1] << "\n";
}
}

Also, how would I make the overall array ("arrays") a pointer so that I can add new arrays to it? I made a preliminary function, but it doesn't work (note "paths" is the overall array):

void addPath (void)
{

int n = getArrayLength(paths), i = 0;
bool (*newPaths)[n + 1];

while (i < n) {

    newPaths[i] = paths[i];

    ++i;
}

delete [] paths;

newPaths[n] = tempPath;

paths = newPaths;
}

Hopefully this isn't to confusing or absurd, and thank you for your help.

1
  • 1
    Possible duplicate of any of the dozens of questions that appear if you search for "c++ array of pointers" Commented Apr 7, 2011 at 21:53

3 Answers 3

1

It appears that you're looking for std::vector:

#include <vector>

std::vector<std::vector<bool> > paths;

Note, however, that std::vector<bool> isn't a normal "container", and doesn't support all the operations of a normal container like vector<any_type_other_than_bool> would.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use malloc. Of course, that's kind of C code, not C++:

#include <cstring>
#include <cstdlib>

size_t ptrArraySize = 3; 
bool** arrays = (bool**) malloc(ptrArraySize * sizeof(bool*));

Or, you could do as Jerry Coffin suggested. However, this doesn't give you a vector with pointers to vectors. It gives you a vector of vectors (so stack allocated, not on the heap). To get a vector of pointers to vectors, you could do something like:

#include <vector>

std::vector<std::vector<bool> * > ptrVector;
std::vector<bool> * vectorA = new std::vector<bool>();
vectorA->push_back(true);
ptrVector.push_back(vectorA);

Another possibility is using one of boost::scoped_array or boost::shared_array, depending on your needs.

Comments

0

bool (*arrays)[3] declares arrays to be a pointer to an array of 3 bools -- you want an array of 3 pointers to bools, or bool *arrays[3]. To make a pointer to that dynamically, you want just bool **arrays = new bool*[3];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.