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;
/* 数组作为参数传给函数时传的是指针而不是数组,传递的是数组的首地址,
如:
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;
}