龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C和C++语言学习总结(一)(4)

时间:2009-12-22 15:42来源:未知 作者:admin 点击:
分享到:
动态生成内存的代码 ------------------------------------------ 正确代码: void GetMemory(char **p, int num) { *p = (char *)malloc(sizeof(char) * num); } char* GetMemory2(int num) { char* p

  动态生成内存的代码

------------------------------------------

正确代码:

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 值.应该拆分为两个独立的语句:

精彩图集

赞助商链接