C: 关于函数返回值的小思考
1.函数的返回值只能有一个,但如果希望获得函数中的多个值,可以采用指针的方式。
2.注意向函数传递列指针的形式:
void InputArray(int *p, int m, int n){ //这里传入的是二维数组,但形参指针是一维形式
int i, j;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
printf("input the number:\n");
scanf("%d", &p[ i * N + j] );//也可以换成 p + i * N + j
}
}
}
附上求二维数组最大值及其位置的代码:
#include <stdio.h>
#define N 10
void InputArray(int *p, int m, int n);
int FindMax(int *p, int m, int n, int *pRow, int *pCol);
int main() {
int a[N][N] = {0};
int m, n;
int row, col;
printf("input m, n:\n");
scanf("%d, %d", &m, &n);
InputArray(a, m, n);
printf("The max number is :%d, row: %d, col: %d\n ", FindMax(a, m, n, &row, &col), row + 1, col + 1);
return 0;
}
void InputArray(int *p, int m, int n){
int i, j;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
printf("input the number:\n");
scanf("%d", &p[ i * N + j] );//也可以换成 p + i * N + j
}
}
}
int FindMax(int *p, int m, int n, int *pRow, int *pCol){//希望返回值,以及行数列数,故后两个用的是指针
// int Row = 0, Col = 0;
int k = p[0];
int i, j;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
if(p[i * N + j] > k){
k =p[ i * N + j] ;//也可以换成*(p + i * N + j)
*pRow = i;
*pCol = j;
}
}
}
return k;
}
也可将FindMax改为void型,相应的改变如下:
#include <stdio.h>
#define N 10
void InputArray(int *p, int m, int n);
void FindMax(int *p, int m, int n, int *pRow, int *pCol);
int main() {
int a[N][N] = {0};
int m, n;
int row, col;
printf("input m, n:\n");
scanf("%d, %d", &m, &n);
InputArray(a, m, n);
FindMax(a, m, n, &row, &col);//因为函数没有返回值,所以FindMax不能写在printf中了
printf("The max number is :%d, row: %d, col: %d\n ", a[row][col], row + 1, col + 1);//由于是指针形式传递,所以row和col的值可以获取
return 0;
}
void InputArray(int *p, int m, int n){
int i, j;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
printf("input the number:\n");
scanf("%d", p + i * N + j );
}
}
}
void FindMax(int *p, int m, int n, int *pRow, int *pCol){
// int Row = 0, Col = 0;
int k = p[0];
int i, j;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
if(p[i * N + j] > k){
k = *(p + i * N + j);
*pRow = i;
*pCol = j;
}
}
}
// return k;
}