Pointer to an address of a row in a 2 dim array

Write your question here.

Hi,

I'm having a problem assigning a pointer with the address of a row in a 2 dimensional array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int FindMaxArray(int array[0][NUM_ELEMS], int NUM_ARRAYS, int **arrayPtr)
{
  int maxNum[NUM_ELEMS];
  int temp = 0;
  for (int i = 0; i < NUM_ARRAYS; i++)
  {
    maxNum[i] = CalcArraySum(array[i],NUM_ELEMS);
    if (maxNum[i] > temp)
    {
      temp = maxNum[i];
      **arrayPtr = &array[i]; //error: invalid conversion from int (*)[4] to 
                              //int [-fpermissive]
    }
  }
}


CalcArraySum derives the sum of each row
I'm trying to pass **arrayPtr to another function that would display the row with the biggest sum

1
2
3
4
5
6
7
void DispArray(int array[], int numItems)
{
  for (int i = 0; i < numItems - 1; i++)
  {
    cout << array[i] << " + ";
  }
}

arrayPtr will be passed into the first argument int array[] in void DispArray

This is what is passed to the function in main()
1
2
int *arrayPtr;
sum = FindMaxArray(intArrays,NUM_ARRAYS,&arrayPtr);


intArrays is just a 2 dimensional array with 5 rows, 4 elements each row.
Any idea what's going on and how to fix this problem?
Thanks a lot in advance
Last edited on
&array[i] gives you a pointer to an array. The address is correct but the type is not.

You have to write
 
*arrayPtr = array[i];
or
 
*arrayPtr = &array[i][0];
Thanks a lot, I managed to get it work by doing (*arrayPtr) = &array[i][0] which is the same with your alternative way of writing the code
If you do have time, could you please explain a little bit on my the second element must be 0 and not some other number? I'm just not sure if I'm understanding it correctly
OK, so let's start with a simpler example.


Let's say we have the following array and pointer:

1
2
int myArray[5] = {3, 7, 11, 17, 47};
int* ptrToFirstElement;

To make the pointer point to the first element in the array we can simply write:

 
ptrToFirstElement = myArray;

Or, if we want, we can use the address-of operator on the first element in the array:

 
ptrToFirstElement = &myArray[0];


In your code, the array that we want to get a pointer to the first element of is array[i], and the pointer that should point to the first element in this array is *arrayPtr.

Substituting myArray with array[i] and ptrToFirstElement with *arrayPtr in my code above gives us the the following:

 
*arrayPtr = &array[i][0];
Last edited on
Topic archived. No new replies allowed.