C和C++语言学习总结(一)(4)
动态生成内存的代码
------------------------------------------
正确代码:
void GetMemory(char **p, int num)
{
*p = (char *)malloc(sizeof(char) * num);
}
char* GetMemory2(int num)
{
char* p = (char *)malloc(sizeof(char) * num);
return p;
}
------------------------------------------
错误的代码:
void GetMemory3(char *p, int num)
{
p = (char *)malloc(sizeof(char) * num);
}
------------------------------------------
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100); // 注意参数是&str,而不是str
strcpy(str, "hello");
cout < < str < < endl;
free(str);
str=NULL;
str=GetMemory2(100);
strcpy(str, "hello");
cout < < str < < endl;
free(str);
str=NULL;
GetMemory3(str, 100); // str 仍然为NULL
strcpy(str, "hello"); // 运行错误
cout < < str < < endl;//运行错误
free(str);//运行错误
}
strcpy代码
char* strcpy(char* strDest,const char* strSrc)
{
if(strDest==NULL||strSrc==NULL) return NULL;
char* pStr=strDest;
while((*strDest++=*strSrc++)!=')
NULL;
return pStr;
}
复合表达式
d = (a = b + c) + r ;
该表达式既求a 值又求d 值.应该拆分为两个独立的语句:
- 上一篇:C和C++语言学习总结(二)
- 下一篇:游戏封面欣赏





