求解整型數(shù)組長度可以使用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
++
)?
//
這里卻不能正確得到數(shù)組長度,單步執(zhí)行時發(fā)現(xiàn)for循環(huán)未執(zhí)行
????
{
????????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
++
)??
//
這里可以正確求解數(shù)組長度
????????cout
<<
a[i]
<<
"
??
"
;
????system(
"
pause
"
);
????
return
(
0
);
}
搜集資料得到的答案是,數(shù)組傳入函數(shù)時,傳入的是指針,并不是我想的那樣拷貝副本,
所以此時sizeof(a)/sizeof(int)等于1,條件不符合,跳出循環(huán)。
這里只能添加一個數(shù)組長度的參數(shù):
#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
);
}
不知道各位高手有什么好辦法,小弟謝了!
?????????????
如果C++“真的"傳遞了數(shù)組拷貝,我敢保證,世界上從來就沒有C++這門語言。
傳遞數(shù)組長度的問題很“老”了,這個問題的解決方法也很多,你用的是一種比較簡單常見的方法,但其實已經(jīng)足夠。還有一些非常"技巧"或者"OO”的方法,參考<<Thinking in C++ v2>>和<<Imperfect C++>>。
如果數(shù)組作形參,必須提供數(shù)組的長度,否則就會出現(xiàn)指針退化的
當然,得到的,很多都是錯誤的,后來無奈,跟你用了一樣的方法...
不知道有誰能有更簡便的方法求出整型數(shù)組的長度..