Click here to Skip to main content
15,911,711 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<iostream.h>
const int kStudents = 25;
const int kProblemSets = 10;

// This function returns the highest grade in the Problem Set array.
int get_high_grade(int *a, int cols, int row, int col)     //1. how is the pointer allocated
 {
 int i, j;
 int highgrade = *a;

 for( i = 0; i < row; i++)
 for( j = 0; j < col; j++)
 if ( *(a + i * cols + j) > highgrade)    //2. How does this line work?
 highgrade = *(a + i*cols + j);
 return highgrade;
}

int main() {
 int grades[kStudents][kProblemSets] = { {75, 70, 85, 72, 84},
 {85, 92, 93, 96, 86}, {95, 90, 83, 76, 97}, {65, 62, 73, 84, 73} };
 int std_num = 4;
 int ps_num = 5;
 int highest;

 highest = get_high_grade( (int *)grades, kProblemSets, std_num, ps_num);
 cout << "The highest problem set score in the class is " << highest << endl;

 return 0;
}


i am new to programming , i want to know about the comment i have put inside the code.
there are two comments, can anyone please explain them.
in the second comment, i want to know how the pointer is making the code works like 1-d array.
Posted

1 solution

1. The array is being passed as a parameter and must hence be allocated by the caller, in this case main. Main allocates the 2D array as auto-variable, i.e. on the stack. See the definition of the grades array.

2. a is a pointer to the 2D array. The expression (i * cols + j) calculates the number of the cell in the 2D array, assuming that the array cells are counted left-to-right, top-to-bottom. Hence there are cols cells in one row. i is the row index and j is the column index. By adding that cell index to the pointer a you arrive at the nth element in the array and *( ...) dereferences this pointer and accesses the contents of that array cell.
 
Share this answer
 
Comments
bhawin parkeria 8-Jul-13 8:50am    
1. what is (int *)grades?

2. does it behaving like a 1-d array?
nv3 8-Jul-13 9:17am    
The declaration in get_high_grade expects a 1D array, hence the parameter declaration as "int* a". But grades is technically seen an array of rows, i.e. an array of int-arrays. Without the cast, the compiler would complain. But the cast is in this case valid, because the starting address of the 2D array can truly be seen as the address of the first element.

Syntactically correct you could write:
highest = get_high_grade(&grades[0][0], ...
and you would not need that ugly cast.
bhawin parkeria 8-Jul-13 17:43pm    
thnx a lot
its pleasure to accept the solution and your knowledge
bhawin parkeria 8-Jul-13 17:43pm    
thnx a lot
nv3 8-Jul-13 18:07pm    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900