运算符与函数

two example:

1.new -- malloc()

使用上,a)new 运算符定义时封装了malloc()函数。 new返回为 固定类型的,比如int *a= new int[10]; malloc()返回为void*,需要强制类型装换,比如:int *a=(int *) malloc(sizeof(int)*10);

b)注意到,malloc需要指定数据长度,sizeof(int)(10),而new直接int[10]。

总之是要告诉编译器,分配多大的内存,返回指向这块内存的指针。

2.sizeof -- strlen(char *)

#include<iostream>
using namespace std;


void Func(char str_arg[200])  //传参时退化为数组名便退化为指针,sizeof不再是数组的长度
/* 数组作为参数传给函数时传的是指针而不是数组,传递的是数组的首地址, 
如: 
fun(char [8]) 
fun(char []) 
都等价于 fun(char *) 

在C++里参数传递数组永远都是传递指向数组首元素的指针,编译器不知道数组的大小 
如果想在函数内知道数组的大小, 需要这样做: 
进入函数后用memcpy拷贝出来,长度由另一个形参传进去 
fun(unsiged char *p1, int len) 

unsigned char* buf = new unsigned char[len+1] 
memcpy(buf, p1, len); 
} */
{  
    int m = sizeof(str_arg); //4    //指针的大小为4  
    int n = strlen(str_arg); //5    //对数组求长度,str_arg后面的那个2没有任何意义,数组已经退化为指针了  
    printf("%d\n",m);  
    printf("%d\n",n);  
}  
int main()
{



char test[6]="Hello";
char *test2="Hello";
cout<<sizeof test<<endl;//sizeof为操作符,此处对变量名可不加括号,但是如果sizeof(classname)必须加括号
cout<<sizeof(test)<<endl;//6
cout<<sizeof(test2)<<endl;//4
cout<<strlen(test)<<endl;//5
cout<<strlen(test2)<<endl;//5
Func(test);




char str[20]="0123456789"; 
int a=strlen(str); //a=10; 
int b=sizeof(str); //b=20; 
cout<<a<<endl;
cout<<b<<endl;

int* c=(int*)malloc(sizeof(int)*100);//没法自动计算
int *d= new int[100];//自动计算100个int
cout<<(sizeof c)<<endl;
cout<<(sizeof d)<<endl;
system("pause");
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值