I have dynamically created a 2d bool array and was wondering if i could create a pointer that points to the second column of the array.

Recommended Answers

All 4 Replies

If you mean can you have a pointer that points to the contents of a column, such that you pass that pointer to a function expecting a 1D array and it will process that column, NOPE.

You can have a pointer which points to the second element of any given row, but will just give you access that that row, starting at that element.

No, I want to point to the first element of the second column and then traverse to the bottom of the column and do some calculations on the individual elements.

Then you'll have to deal with the full 2D array, traverse row to row, accessing only the column index you're interested in.

If you have an existing function that takes a 1D parameter and you want it to deal with a column from the 2D, I'd make a copy of the column into a temporary 1D array and pass that to the function.

You could do it something like this, which increments the pointer by 2 on every loop iteration.

int main()
{
    int array[10][2] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
    int* p = (int *)&array[0][1];
    for(int i = 0; i < 10; i++)
    {
        std::cout << *p << '\n';
        p += 2;
    }
   return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.