例1:
#include
<iostream>
using
namespace
std;
int
main()
{
int
array[2][3] = { { 1, 2, 3 },{ 4, 5, 6 } };
int
*ptr = (
int
*)array;
int
i = 0;
while
(i < 6)
{
cout
<<
" "
<<
ptr[i];
i++;
}
return
0;
}
输出:
分析:可看出array[0][2]和array[1][0]地址是连续的。
例2:
#include
<iostream>
using
namespace
std;
int
main()
{
int
array[2][3] = { { 1, 2, 3 },{ 4, 5, 6 }};
int
**ptr = (
int
**)malloc(2 *
sizeof
(
int
));
if
(ptr ==
NULL
)
{
cout
<<
"malloc error!"
<<
endl;
exit(1);
}
for
(
int
i = 0; i < 2; i++)
{
ptr[i] = (
int
*)malloc(3 *
sizeof
(
int
));
if
(ptr[i] ==
NULL
)
{
cout
<<
"malloc error!"
<<
endl;
exit(1);
}
for
(
int
j = 0; j < 3; j++)
{
ptr[i][j] = array[i][j]; // 因为在堆上分配了内存空间
}
}
for
(
int
i = 0; i < 2; i++)
{
for
(
int