Assigning an Array of Pointers to an Array

Mar 26, 2011 at 5:25am
For some reason this code generates a segfault, any ideas why?

1
2
3
4
5
6
7
bool Memory[8][100];
bool *ptrMemory[8][100];
for (int row=0; row<8; row++)
    {
    for (int col=0; col<100; col++)
        *ptrMemory[row][col] = &Memory[row][col];
    }


Any help is greatly appreciated.
Last edited on Mar 26, 2011 at 6:19am
Mar 26, 2011 at 5:34am
So what you want an pointer to an 8*100 array in each slot of an 8*100 array?
1
2
3
4
5
6
7
8
bool Memory[8][100];

bool ptrMemory[8][100];
for (int row=0; row<8; row++)
    {
    for (int col=0; col<100; col++)
        ptrMemory[row][col] = &Memory[row][col];
    }
Last edited on Mar 26, 2011 at 5:36am
Mar 26, 2011 at 6:18am
Thanks. Pointers are a pain, how come I don't need to designate it as a pointer at declaration time anyways?
Mar 26, 2011 at 7:50am
kevinkjt2000 wrote:
So what you want an pointer to an 8*100 array in each slot of an 8*100 array?

1
2
3
4
5
6
7
8
bool Memory[8][100];

bool ptrMemory[8][100];
for (int row=0; row<8; row++)
    {
    for (int col=0; col<100; col++)
        ptrMemory[row][col] = &Memory[row][col];
    }



That makes no sense
Last edited on Mar 26, 2011 at 7:51am
Mar 26, 2011 at 7:56am
But it did work correctly.
Mar 26, 2011 at 8:20am
All that code does is set all the elements of the ptrMemory array to true.
It does not do as it says- pointer to an 8*100 array in each slot of an 8*100 array - because this line has a error bool ptrMemory[8][100];

Mar 26, 2011 at 1:07pm
Why don't you create 1 pointer( rather than 8 * 100 pointers ) for the array and then just change the pointer to look at the index you need to use?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	bool myArray[ 2 ][ 5 ] =
	{ { true, false, false, true, false },
	{ false, true, true, true, false } };

	//create the pointer and get it to look at index 0, 0
	bool *ptrMyArray = &myArray[ 0 ][ 0 ];

	for( int i = 0; i < 2; i++ )
	{
		for( int j = 0; j < 5; j++ )
		{
			//iterate through the index's using the for loop's
			ptrMyArray = &myArray[ i ][ j ];

			std::cout << "myArrayT[ " << i << " ][ " << j << " ]: \t" << myArray[ i ][ j ] << '\n';
			std::cout << "ptr\t[ " << i  << " ][ " << j << " ]: \t" << *ptrMyArray << "\n\n";
		}
		std::cout << '\n';
	}
Last edited on Mar 26, 2011 at 1:08pm
Mar 26, 2011 at 8:40pm
I am guessing the earlier suggestion worked correctly since arrays and pointers are so similar? Sorry if I seem like a total C++ noob, but I am.
Topic archived. No new replies allowed.