1.函数参数
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
void add(int score[], int size) {//传递数组,需要定义数组中元素个数
cout << "增加后:";
for (int i = 0; i < size; i++) {
score[i] += size;
cout << score[i]<<" ";
}
}
void defaultPara(int score[], int size = 3,int addNum=5) {//默认参数后不可以再有形参
cout << "再次增加后:";
for (int i = 0; i < size; i++) {
score[i] += addNum;
cout << score[i] << " ";
}
}
int main(void) {
int score[3] = { 60,70,80 };
cout << "增加前:";
for (int i = 0; i < 3; i++) {
cout << score[i] << " ";
}
cout << endl;
add(score, 3);
defaultPara(score);
system("pause");
return 0;
}
函数的名字相同, 参数个数不同,函数也不同
2.杨辉三角
#include <iostream>
#include <Windows.h>
#include <iomanip>
#define MAX 16
using namespace std;
int main(void) {
int N;
int arr[MAX][MAX];
cout << "请输入行数:";
cin >> N;
//初始化数组
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (j == 0 || i == j) {
arr[i][j] = 1;
}
else {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
}
}
}
system("cls");
//打印数组
for (int i = 0; i < N; i++) {
cout << setw((N - i) * 3) << " ";
for (int j = 0; j <= i; j++) {
cout << setw(6) << arr[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
初始化中设置数据
3.指针数组
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int main(void) {
int girls[3][3] = {
{162,165,161},
{169,167,163},
{165,164,166}
};
//指针数组,每个元素都是一个指针
int *p[2] = {
&girls[0][0],//最高的girl
&girls[0][0],//最低的girl
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (*p[0] < girls[i][j]) {
p[0] = &girls[i][j];
}
if (*p[1] > girls[i][j]) {
p[1] = &girls[i][j];
}
}
}
printf_s("最高者:%d,最低者:%d", *p[0], *p[1]);
system("pause");
return 0;
}
一级指针int *p相当于一个整数
4.数组指针
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int main(void) {
int girls[4][3] = {
{162,165,161},
{169,167,163},
{165,164,166},
{168,170,155}
};
//指向三个成员的数组指针,可以通过对指针p++操作下一行一维数组
int (*p)[3] = &girls[0];
int *low = girls[0];
//数组下标法
/*
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
printf_s("%d ", (*p)[j]);
}
printf_s("\n");
p++;
}
*/
//指针访问法
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
printf_s("%d ", *((*p)+j));
if (*low > *((*p) + j)) {
low = (*p) + j;
}
}
printf_s("\n");
p++;
}
printf_s("最矮的女生为:%d", *low);
system("pause");
return 0;
}
在二维数组中,数组指针可以通过对指针加减(p+1)操作下一个一维数组。
5.函数指针
#include <stdio.h>
#include <Windows.h>
#include <stdlib.h>
int compare_int(const void* a,const void* b) {
printf_s("指针调用了函数\n");
int* a1 = (int*)a;//强制转换
int* b1 = (int*)b;
return *b1 + *a1;
}
int main(void) {
int x = 10, y = 20;
int sum = 0;
//函数指针的定义:函数声明移过来,把函数名改为(*xxx)
int (*fp)(const void*, const void*);
fp = &compare_int;//把函数地址给函数指针
sum= (*fp)(&x, &y);//调用函数方式1
//fp(&x, &y);//调用函数方式2
printf_s("sum=%d", sum);
system("pause");
return 0;
}