Been working on an assignment that requires creating and traversing 2D array of integers, but without using array notation, such as a[1][2] or even ((a+i)+j). It is required to use pointer arithmetic to access each individual element.
So far my approach has been to allocate it as such. Included are comments that show what I think my code should be accomplishing, feel free to correct me otherwise.
int **a; // 2d array, or pointer to array of pointers
row = 5;
count = 5;
// allocate space
a = new int* [row]; // create array of pointers
int *p = *m; // point to first array
for (int r = 0; r < row; r++)
{
a = new int [col]; // create space within each array
a++;
}
Row and columns are dynamic, and is passed in as parameters in the function. 5 is just used as an example here.
To fill the 5 x 5 2d array with elements (example 5), I use the following :
int *pRow = *a; // get array of pointers
int *pElement = &pRow[0]; // get first element from the first array
int r = 0;
int c = 0;
while (r < row)
{
while (c < col)
{
int element = 5;
*pElement = element; // set first element to 5
pElement++; // go to next element
c++;
}
c = 0;
r++;
}
The problem is that *pElement = element throws a EXC_BAD_ACCESS error so there's something that I'm doing wrong.
Could anyone point out my mistake or correct my understanding of pointers, if it is found wanting?
--
Also, as a side note, is it correct to say,
int *pRow = *a;
int *pElement = &pRow[0];
accesses the same thing (which is the first element) as
int *pElement = &**a[0];