1、
char* p = "abcdef";
cout << sizeof(p) << endl;//c语言默认地址长度4字节
//统计一个指针的大小,32位系统指针占4字节,64位系统指针占8字节
cout << sizeof(*p) << endl;//1
//4
b//
就是定义一个指针变量p。并让str指向"abcdef""在内存中的首地址.如果你要用这个字符串,可以用下标的形式访问p[0]。
2、
char q[] = "abcdef";
cout << sizeof(q) << endl;//数组求大小
//7 /0结尾
b//
3、
在c语言里面求指针变量的值:printf("addr = %p\n",p);
C++: cout << (void*)p << endl;
cout << (void*)p << (void*)p << endl;//p
cout<<*(p+1)<<' '<<static_cast<void*>(p+1)<<endl;//p+1
const char *pszStr = "this is a string";
cout << "字符串起始地址值: " << static_cast<const void *>(pszStr) << endl;//常量的
区别:
1、求大小指针形式的 sizeof(p) 4 ,数组形式返回数组长的(算上\0)
strlen
strlen 是一个函数,它用来计算指定字符串 str 的长度,但不包括结束字符(即 null 字符)
4、还有一个比较有意思的\0
#include <iostream>
//#include <stdio.h>
//#include <stdlib.h>
using namespace std;
int main()
{
char p[] = "abcdef";
cout << p << endl;
cout << sizeof(p) << endl;
p[2] = '\0';
cout << p << endl;
cout << sizeof(p) << endl;
return 0;
}
也就是说中间加\0会改变输出但不会改变大小
6、还有一个指针做形参退化问题
sizeof大小就是一个普通指针的大小,但是值还有。贵族变平民,像是char *p了
#include <iostream>
//#include <stdio.h>
//#include <stdlib.h>
using namespace std;
void fun(char *p)
{
cout << "fun:sizeof(p):" << sizeof(p) << endl;
cout << "fun:p: "<<p << endl;
cout << "fun:p[4]: "<<p[4] << endl;
}
int main()
{
char p[] = "abcdef";
cout << p << endl;
cout << sizeof(p) << endl;
fun(p);
return 0;
}
测试用例
#include <iostream>
//#include <stdio.h>
//#include <stdlib.h>
using namespace std;
int main()
{
char* p = "abcdef";char* a = "abcdef";
cout << "sizeof(p)" << sizeof(p) << p[1] << endl;//c语言默认地址长度4字节
cout << (void*)p << endl;
cout<<*(p+1)<<' '<<static_cast<void*>(p+1)<<endl;
cout << "%p" << p << endl;
cout << "%p" << a << endl;
printf("addr = %p\n",p);
printf("addr = %p\n",a);
char q[] = "abcdef";
cout << "sizeof(q)" << sizeof(q) << q[6] << endl;
cout << "(q)" << q << *q << endl;
return 0;
}