指针变量求大小sizeof,求长度不算\0的strlen,以及C++求指针变量的值

8 篇文章 0 订阅

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;
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值