利用指针查找元素在二维数组的位置
时间: 2024-05-04 16:15:23 浏览: 23
假设要查找的元素为x,二维数组为arr,数组的行数为n,列数为m。
1. 遍历二维数组,逐个比较元素是否为x。
2. 如果找到了x,可以记录其所在的行数i和列数j,然后退出遍历。
3. 如果遍历完数组仍未找到x,则返回不存在。
以下是实现代码:
```
int findElement(int** arr, int n, int m, int x, int* row, int* col) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] == x) {
*row = i;
*col = j;
return 1; // 找到了x
}
}
}
return 0; // 没有找到x
}
```
调用方式:
```
int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int* p[3] = {arr[0], arr[1], arr[2]}; // 将二维数组转化为指针数组
int row, col;
int found = findElement(p, 3, 4, 7, &row, &col); // 查找元素7
if (found) {
printf("元素7在二维数组中的位置为(%d, %d)", row, col);
} else {
printf("元素7不存在二维数组中");
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)