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
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
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: