q******0 发帖数: 15 | 1 See the code below. I am confused that "len = 5" from main function, "len =
4" from RemoveDuplicate function. When does terminate '\0' count? Thanks.
#include
using namespace std;
void RemoveDuplicate(char str[])
{
int len = sizeof(str)/sizeof(str[0]);
cout << "len = " << len << endl;
}
int main()
{
char a[] = "abcd";
int len = sizeof(a)/sizeof(a[0]);
cout << "len = " << len << endl;
RemoveDuplicate(a);
return 0;
} |
l*****a 发帖数: 14598 | 2 please use "abcde" as your input and check the result
=
【在 q******0 的大作中提到】 : See the code below. I am confused that "len = 5" from main function, "len = : 4" from RemoveDuplicate function. When does terminate '\0' count? Thanks. : #include : using namespace std; : void RemoveDuplicate(char str[]) : { : int len = sizeof(str)/sizeof(str[0]); : cout << "len = " << len << endl; : } : int main()
|
i**********e 发帖数: 1145 | 3 Try this and figure out why:
void foo(int str[])
{
int len = sizeof(str)/sizeof(str[0]);
cout << "len = " << len << endl;
}
int main()
{
int a[] = {1,2,3,4};
int len = sizeof(a)/sizeof(a[0]);
cout << "len = " << len << endl;
foo(a);
return 0;
} |
r*****k 发帖数: 1281 | 4 void RemoveDuplicate(char str[])
{
int len = sizeof(str)/sizeof(str[0]);
cout << "len = " << len << endl;
}
这上面这段code中,sizeof(str)是计算“the size of the pointer represented by
the array identifier”, which is always 4. |
S**I 发帖数: 15689 | 5 not necessarily always 4; size of a pointer is implementation defined.
by
【在 r*****k 的大作中提到】 : void RemoveDuplicate(char str[]) : { : int len = sizeof(str)/sizeof(str[0]); : cout << "len = " << len << endl; : } : 这上面这段code中,sizeof(str)是计算“the size of the pointer represented by : the array identifier”, which is always 4.
|
r*****k 发帖数: 1281 | 6 Yes, you are right. I meant that in lz's test case, it's always 4.
【在 S**I 的大作中提到】 : not necessarily always 4; size of a pointer is implementation defined. : : by
|
a*****a 发帖数: 495 | 7 ...not
【在 r*****k 的大作中提到】 : Yes, you are right. I meant that in lz's test case, it's always 4.
|
p*i 发帖数: 411 | 8 If you are on a 64bit environment and compiles the source code in 64bit mode
, the main function will output len = 5 (length of the C string) and the
RemoveDuplicate function will output len=8, which is exactly sizeof(char*)/
sizeof(char)
=
【在 q******0 的大作中提到】 : See the code below. I am confused that "len = 5" from main function, "len = : 4" from RemoveDuplicate function. When does terminate '\0' count? Thanks. : #include : using namespace std; : void RemoveDuplicate(char str[]) : { : int len = sizeof(str)/sizeof(str[0]); : cout << "len = " << len << endl; : } : int main()
|