求解整型数组长度可以使用sizeof(a)/sizeof(int),当今天我编写插入排序时遇到个问题,代码如下:
#include
<
iostream
>
using
namespace
std;
int
insertsort(
int
a[])

{
int
j,key;
for
(
int
i
=
1
;i
<
sizeof
(a)
/
sizeof
(
int
);i
++
)
//
这里却不能正确得到数组长度,单步执行时发现for循环未执行
{
key
=
a[i];
j
=
i
-
1
;
while
(a[j]
>
key
&&
j
>=
0
)

{
a[j
+
1
]
=
a[j];
j
--
;
}
a[j
+
1
]
=
key;
}
return
(
0
);
}
int
main()

{

int
a[]
=
{
2
,
6
,
9
,
3
,
5
,
8
,
1
,
6
,
3
,
8
}
;

insertsort(a);
for
(
int
i
=
0
;i
<
sizeof
(a)
/
sizeof
(
int
);i
++
)
//
这里可以正确求解数组长度
cout
<<
a[i]
<<
"
"
;
system(
"
pause
"
);
return
(
0
);
}
搜集资料得到的答案是,数组传入函数时,传入的是指针,并不是我想的那样拷贝副本,
所以此时sizeof(a)/sizeof(int)等于1,条件不符合,跳出循环。
这里只能添加一个数组长度的参数:
#include
<
iostream
>
using
namespace
std;
int
insertsort(
int
a[],
int
n)

{
int
j,key;
for
(
int
i
=
1
;i
<
n;i
++
)

{
key
=
a[i];
j
=
i
-
1
;
while
(a[j]
>
key
&&
j
>=
0
)

{
a[j
+
1
]
=
a[j];
j
--
;
}
a[j
+
1
]
=
key;
}
return
(
0
);
}
int
main()

{

int
a[]
=
{
2
,
6
,
9
,
3
,
5
,
8
,
1
,
6
,
3
,
8
}
,n;
n
=
(
sizeof
(a)
/
sizeof
(
int
));
insertsort(a,n);
for
(
int
i
=
0
;i
<
n;i
++
)
cout
<<
a[i]
<<
"
"
;
system(
"
pause
"
);
return
(
0
);
}
不知道各位高手有什么好办法,小弟谢了!