指针分配给二维数组 [英] pointer allocation to 2-d array

查看:116
本文介绍了指针分配给二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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我是编程的新手,我想知道我在代码中添加的注释。

有两条评论,任何人都可以解释一下。

在第二条评论中,我想知道指针如何使代码像1-d数组一样工作。



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.

推荐答案

1。该数组作为参数传递,因此必须由调用者分配,在本例中为main。 Main将2D数组分配为自动变量,即在堆栈上。查看grade数组的定义。



2. a是指向2D数组的指针。表达式(i * cols + j)计算2D阵列中的单元格数,假设阵列单元从左到右,从上到下计数。因此,在一行中有cols细胞。我是行索引,j是列索引。通过将该单元格索引添加到指针a,您到达数组中的第n个元素,并且*(...)取消引用该指针并访问该数组单元格的内容。
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.


这篇关于指针分配给二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆