多维数组的元素在内存中的地址是连续的,比如:
int a[2][3] = {{1,2,3},{4,5,6}};
则该数组在内存中的位置为:
1 2 3 4 5 6
sizeof a/sizeof (int)就是数组的全部元素数量;
sizeof a/sizeof (a[0])就是数组的第一维的数量,这里的结果是2,因为a的第一维的数量为2。
/*************************一*****************************/
#include <iostream>
using namespace std;
int main()
{
int a[2][3];
// 定义一个指向数组第一个元素的常指针beg,由于编译器的类型
// 检查不会让你将普通一维指针(如下,多维指针比如int** a)
// 指向多维数组,而多维数组的数据结构其实和一维数组相同(如
// 上介绍),所以你需要将其重新解释为一维数组,然后再将其首
// 地址赋给beg。
int* const beg = reinterpret_cast<int*>(a);
// sizeof a/sizeof (int)就是所有元素的个数,所以end指向数组
// 中的最后一个元素之后的位置
int* const end = beg + sizeof a/sizeof (int);
cout << "第一行: ";
// 当作一维数组依次赋值
for(int *p = beg; p != end; ++p)
{
// 当beg到达beg + 2*3/2的位置时第一行(或列)结束
if(p == beg + sizeof a[0]/sizeof a[0][0])
cout << "第二行: ";
// 依次输入
cin >> *p;
}
// 依次打印
for(int *p = beg; p != end; ++p)
{
// 解释同上,其实是一维数组的数据结构但我们为了让它易于理解
// 一些所以将其打印为横纵二维排列
if(p == beg + sizeof a[0]/sizeof a[0][0])
cout.put('\n');
// 依次打印
cout << *p << ' ';
}
}
/*************************二*****************************/
#include <iostream>
using namespace std;
const char* month(int n)
{
// 12个月是不变的,声明为静态免去每次调用的重复声明带来额外开销
static char months[13][4] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
// months + n就是第n个月的char[4],其他原理同代码一,需要重新解释
return reinterpret_cast<char*>(months + n);
}
int main()
{
for(int i = 0; i < 12; ++i)
{
// 格式而已,为了看着整齐点......
cout.width(2);
cout << i + 1 << "月: " << month(i) << '\n';
}
}
/*************************三*****************************/
#include <iostream>
using namespace std;
int main()
{
// 全部原理同代码一
int a[][3] = {3, 8, 6, 2, 4, 9};
int* const beg = reinterpret_cast<int*>(a);
int* const end = beg + sizeof a/sizeof (int);
int* p = beg, sum = 0;
// 当作一维数组理解
cout << "前三元素: ";
while(p != beg + 3)
{
sum += *p;
// *p++等价于*(p++)
cout << *p++ << ' ';
}
cout << "和: " << sum << '\n';
// 记住end指向的是数组最后一个元素的后一个位置
p = end;
sum = 0;
cout << "后三元素: ";
while(p != end - 3)
{
// *--p等价于*(--p)
cout << *--p << ' ';
sum += *p;
}
cout << "和: " << sum << '\n';
// 当作一维数组处理
p = beg + 2;
sum = 0;
cout << "中间俩元素: ";
while(p != end - 2)
{
sum += *p;
cout << *p++ << ' ';
}
cout << "和: " << sum << '\n';
}
楼下的你把我的给改糟蹋了,
#include <iostream>
using namespace std;
int main()
{
int *p; // 1
int a[2][3];
int* const beg = reinterpret_cast<int*>(a);
int* const end = beg + sizeof a/sizeof (int);
cout << "第一行: ";
for(p = beg; p != end; ++p) // 1
{
if(p == beg + sizeof a/sizeof a[0])
cout << "第二行: ";
cin >> *p;
}
for(p = beg; p != end; ++p) // 1
{
if(p == beg + sizeof a/sizeof a[0] + 1) // 这里我改掉了,原来我写的代码有问题
cout<<endl; // 2
cout << *p << ' ';
}
cout<<endl; // 2
return 0; // 3
}
1、C++为什么允许你在任意位置而不是代码开头声明变量呢?请你思考一下。
参看《Effective C++》Item 26: Postpone variable definitions as long as possible.
2、在你不需要刷新缓冲区的时候,请使用'\n'来换行而不是endl,否则过多的endl会严重影响你程序的执行效率,虽然代码不长但细节值得注意!
参看《The Standard C++ Library》13.14 Performance Issues.
3、main的返回值可选,我是懒人所以就略去......
参看《The Standard C++ Library》2.2 New Language Features
温馨提示:答案为网友推荐,仅供参考