首先了解数组
char A[5] = { 'a', 'b', 'c' };
int m = strlen(A) / sizeof(char);
int n = sizeof(A) / sizeof(char);
可以得出因为strlen得出的是实际长度,所以m=3;
sizeof得出的是定义长度,所以n=5;
再看下面代码
char A[] = "abcdef";
char *B = "abcdef";
int m=sizeof(A);
int n=sizeof(B);
A直接是指这串字符的首地址,所以m就是这串字符的长度,m=7;
而B是以指针的形式指向字符串,根据规定,指针类型的长度为4,所以n=4;
再看指针类型的字符数组和字符串数组
char A[] = { 'a', 'b', 'c', 'd' };
char *B[] = {"a","b","c","d"};
char *C[] = { "dello", "aorld", "ok", "how do you do" };
cout << *A << " " << *B << " " << *(C+1) << endl;
cout << **B << " " << **C << endl;显示:a a aorld
a d
根据运行结果显示然后再类比char A[]可得;
B和C是指向数组中第n项字符串的指针,所以*B,*C显示的就是每个数组的第1个字符串;
而*B也可看作*B,即为指向第n个字符串的字符串内部指针,所以**B显示的是第一个字符串的第一个字母。
如何求数组指针的大小
此时用到指针类型长度为4的性质。
const char*A[] = { "dello", "aorld", "ok", "how do you do" };
int m = sizeof(A) / sizeof(*A);
cout << m << " " << sizeof(A) << " " << sizeof(*A) << endl;显示:4 16 4
所以得出这个指针字符串数组有4个字符串。
所以若遍历这个指针字符串数组看下面代码
const char*A[] = { "dello", "aorld", "ok", "how do you do" };
int m = sizeof(A) / sizeof(*A);;
for (int i = 0; i < m; i++)
{
cout << *(A + i) << endl;
}