3、文件拷贝的代码
#include
int main(int argc, char* argv[])
{
printf("Hello World!\n");
FILE* in;
FILE* out;
in=fopen("d:\\1.txt","rb");
out=fopen("d:\\2.txt","wb");
char ch=fgetc(in);
while(!feof(in))
{
fputc(ch,out);
ch=fgetc(in);
}
fclose(in);
fclose(out);
return 0;
}
动态生成内存的代码
正确代码:
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++)!=’\0)
NULL;
return pStr;
}
复合表达式
d = (a = b + c) + r ;
该表达式既求a 值又求d 值.应该拆分为两个独立的语句:
a = b + c;
d = a + r;
if (a < b < c) // a < b < c 是数学表达式而不是程序表达式