sizeof是运算符,strlen()是函数。
对于数组A,sizeof(A)求得数组所占内存的大小;
对于指向A的指针p,sizeof(*p)求得数组第一个元素的大小;
int A[] = { 1,2,3,4,5 };
int sizeof_A = sizeof(A);
cout << "size of A: " << sizeof_A << endl;
char B[] = { 'a', 'b', 'c', 'd', 'e' };
int sizeof_B = sizeof(B);
cout << "size of B: " << sizeof_B << endl;
char C[] = "abcde";
int sizeof_C = sizeof(C);
cout << "size of C: " << sizeof_C << endl;
int *p1 = A;
int sizeof_star_p1 = sizeof(*p1);
cout << "size of *p1: " << sizeof_star_p1 << endl;
int sizeof_p1 = sizeof(p1);
cout << "size of p1: " << sizeof_p1 << endl;
char *p2 = B;
int sizeof_star_p2 = sizeof(*p2);
cout << "size of *p2: " << sizeof_star_p2 << endl;
int sizeof_p2 = sizeof(p2);
cout << "size of p2: " << sizeof_p2 << endl;
输出:
strlen()求得从给定内存处到第一个'\0'的长度
int strlen_B = strlen(B);
cout << "strlen of B: " << strlen_B << endl;
int strlen_C = strlen(C);
cout << "strlen of C: " << strlen_C << endl;
int strlen_p2 = strlen(p2);
cout << "strlen of p2: " << strlen_p2 << endl;
char *p3 = C;
int strlen_p3 = strlen(p3);
cout << "strlen of p3: " << strlen_p3 << endl;
输出:
-----------------------------------------------补充1---------------------------------------------------------------------
int main()
{
int a[5] = { 1,2,3,4,5 };
int *p = (int *)(&a + 1);
printf("%d, %d\n", *(a + 1), *(p - 1));
system("pause");
return 0;
}
结果:
-----------------------------------------------补充2---------------------------------------------------------------------
数组名作为参数传递时,数组名退化为指针,因此需要同时传递数组大小。
<pre name="code" class="cpp">void example(char acWelcome[]) {
printf("%d", sizeof(acWelcome));
return;
}
int main() {
char acWelcome[] = "Welcome to Huawei Test";
example(acWelcome);
printf("\n%d\n", sizeof(acWelcome));
system("pause");
return 0;
}
结果: