char a[] = “hello”;
a[0] = ‘X’;
cout << a << endl;
char *p = “world”;
// 注意
p指向常量字符串
p[0] = ‘X’;
// 编译器不能发现该错误
cout << p << endl;
|
// 数组…
char a[] = "hello";
char b[10];
strcpy(b, a); // 不能用
b = a;
if(strcmp(b, a) == 0) // 不能用
if (b == a)
…
|
// 指针…
int len = strlen(a);
char *p = (char *)malloc(sizeof(char)*(len+1));
strcpy(p,a); // 不要用
p = a;
if(strcmp(p, a) == 0) // 不要用
if (p == a)
…
|
char a[] = "hello world";
char *p = a;
cout<< sizeof(a) << endl; // 12字节
cout<< sizeof(p) << endl; // 4字节
|
void Func(char a[100])
{
cout<< sizeof(a) << endl; // 4字节而不是
100字节
}
|
void GetMemory(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
}
|
void Test(void)
{
char *str = NULL;
GetMemory(str, 100); // str 仍然为
NULL
strcpy(str, "hello"); // 运行错误
}
|
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}
|
void Test2(void)
{
char *str = NULL;
GetMemory2(&str, 100); // 注意参数是
&str,而不是str
strcpy(str, "hello");
cout<< str << endl;
free(str);
}
|
char *GetMemory3(int num)
{
char *p = (char *)malloc(sizeof(char) * num);
return p;
}
|
void Test3(void)
{
char *str = NULL;
str = GetMemory3(100);
strcpy(str, "hello");
cout<< str << endl;
free(str);
}
|
char *GetString(void)
{
char p[] = "hello world";
return p; // 编译器将提出警告
}
|
void Test4(void)
{
char *str = NULL;
str = GetString(); // str 的内容是垃圾
cout<< str << endl;
}
|
char *GetString2(void)
{
char *p = "hello world";
return p;
}
|
void Test5(void)
{
char *str = NULL;
str = GetString2();
cout<< str << endl;
}
|
char *p = (char *) malloc(100);
strcpy(p, “hello”);
free(p); // p 所指的内存被释放,但是p所指的地址仍然不变
…
if(p != NULL) // 没有起到防错作用
{
strcpy(p, “world”); // 出错
}
|
void Func(void)
{
char *p = (char *) malloc(100); // 动态内存会自动释放吗?
}
|
class Obj
{
public :
Obj(void){ cout << “Initialization” << endl; }
~Obj(void){ cout << “Destroy” << endl; }
void
Initialize(void){ cout << “Initialization” << endl; }
void
Destroy(void){ cout << “Destroy” << endl; }
};
|
void UseMallocFree(void)
{
Obj *a = (obj *)malloc(sizeof(obj)); // 申请动态内存
a->Initialize(); // 初始化
//…
a->Destroy(); // 清除工作
free(a); // 释放内存
}
|
void UseNewDelete(void)
{
Obj *a = new Obj; // 申请动态内存并且初始化
//…
delete a; // 清除并且释放内存
}
|
void main(void)
{
float *p = NULL;
while(TRUE)
{
p = new float[1000000];
cout << “eat memory” << endl;
if(p==NULL)
exit(1);
}
}
|