一、二维数组
关于第4种,为什么可以省略行数,不能省略列数?
——给出列数就能确定几个元素是一组;而给出了行数,只能确定有几组元素。比如给了两行,
你可以对半分配,你也可以第一行给比第二行多的元素。
二、二维数组数组名
1)查看二维数组所占内存空间
2)获取二维数组首地址
#include <iostream>
using namespace std;
int main()
{
int arr[2][3] =
{
{1,2,3},
{4,5,6}
};
cout << "一共有几行:" << sizeof(arr) / sizeof(arr[0]);
cout << "一共有几列:" << sizeof(arr[0]) / sizeof(arr[0][0]);
system("pause");
return 0;
}
行数代表有几组元素。
#include <iostream>
using namespace std;
int main()
{
int arr[2][3] =
{
{1,2,3},
{4,5,6}
};
cout << "二维数组首地址为:" << (int)arr << endl;
cout << "二维数组第一行地址为:" << (int)&arr[0] << endl;
cout << "二维数组第一行首元素地址为:" << (int)&arr[0][0] << endl;
cout << "二维数组第二行地址为:" << (int)&arr[1] << endl;
system("pause");
return 0;
}
用 & 来获取地址!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int scores[3][3] =
{
{100, 100, 100},
{90, 50, 100},
{60, 70, 80}
};
string names[3] = {"张三", "李四", "王五"};
int i = 0;
for(i=0; i<3; i++)
{
int j = 0;
int sum = 0;
for(j=0; j<3; j++)
{
cout << scores[i][j] << " ";
sum += scores[i][j];
}
cout << names[i] << "的总分为:" << sum << endl;
}
system("pause");
return 0;
}
使用string时要写头文件!
三、函数:将一段经常使用的代码封装起来,减少重复代码。
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能。
1.
main()是一个函数,为程序的入口函数。
int main()
{
return 0;
}
main()括号中没有任何东西,因为main函数中不需要传入任何数据。
return 0代表返回一个正常的退出值。
2.函数的调用:使用定义好的函数。
如Add(a, b);
这边的a不用写成 int a,因为已经定义了函数,所以不用加了。
#include <iostream>
#include <string>
using namespace std;
int Add(int a, int b)
{
return a + b;
}
int main()
{
int a = 10;
int b = 20;
int sum = Add(a, b);
cout << "sum = " << sum << endl;
system("pause");
return 0;
}
在主函数中,a和b都为实际的值,所以在函数调用中称为“实际参数”。
在函数定义时,a和b并没有真实的数据,它只是形式上的一个参数,也就是“形式参数”。
当调用函数时,实参的值会传递给形参。
3.值传递
1.所谓值传递,就是函数调用时实参将数值传入给形参。
2.值传递时,如果形参发生改变,并不会影响实参。
1.
#include <iostream>
using namespace std;
void test_01()
{
cout << "666" << endl;
}
int main()
{
test_01();
system("pause");
return 0;
}
2.
#include <iostream>
using namespace std;
void test_01(int a)
{
cout << "a = " << a << endl;
}
int main()
{
test_01(100);
system("pause");
return 0;
}
3.
#include <iostream>
using namespace std;
int test_01()
{
cout << "666" << endl;
return 666;
}
int main()
{
int a = test_01();
cout << a << endl;
system("pause");
return 0;
}
4.
#include <iostream>
using namespace std;
int test_01(int a)
{
cout << "a = " << a << endl;
return a;
}
int main()
{
int num = test_01(10);
cout << num << endl;
system("pause");
return 0;
}