#include <stdio.h>
#include <string.h>
#include <malloc.h>
第一题
//void GetMemory(char *p)
//{
// p = (char *)malloc(100);
//}
//
1.没有释放
2.传入的指针不是同一个指针
//void Test1(void)
//{
// char *str = NULL;
// GetMemory(str);
// strcpy(str, "hello world");
// printf(str);
//}
第二题
//char *GetMemory(void)
//{
// //不要返回临时变量的引用
// char p[] = "hello world";
// return p;
//}
//
//void Test2(void)
//{
// char *str = NULL;
// str = GetMemory();
// printf(str);
//}
struct mydata
{
int n;
mydata *pNex;
};
//第三题(指向指针的指针)
//
void GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test3(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
free(str);
}
//第四题
//
void Test4(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
str=NULL;//删除之后,重置指针,避免野指针
if(str != NULL)
{
strcpy(str,"world");
printf(str);
}
}
//第五题
//
void Test5()
{
int n=-1;
unsigned int x=100;
unsigned p=(unsigned)n;
if (n<x)//有个类型转换的问题在里面
printf("n<x\n");
else
printf("n>=x\n");
}
//第六题
//
long Test6(short n,short x)
{
long score;
score=n*x;//隐患,可能会超出取值范围
return score;
}
//第七题
//
int Test7(char *pStr,int nLne)
{
char *pTmp=(char*)malloc(nLne);
if (nLne<20)
return 0;//有个逻辑错误,可能会内存泄露
strcpy(pTmp,pStr);
free(pTmp);
return 1;
}
//第八题(new\delete\delete[])
//
void Test8()
{
//int n=100;
//int *p=&n;
int *p1=new int;//初始化
//*p1=200;//赋值
printf("%d",*p1);
delete p1;
/*int *p=new int[5];
*p=100;
*(p+1)=200;
*(p+2)=300;
*(p+3)=400;
*(p+4)=500;
printf("%d\n",*p);
printf("%d\n",*(p+1));
printf("%d\n",*(p+2));
printf("%d\n",*(p+3));
printf("%d\n",*(p+4));
delete [] p;*/
//delete 和 delete [] 不能混着用!!!!
}
#include <iostream>
using namespace std;
//内联函数中,主要实现一些简单的代码
//太过复杂的话直接当做不同函数来用
inline void fun()
{
printf("in fun");
}
void fun2(int n=0,int x=0,int y=0)
{
//带默认参数的函数,默认参数一定要放在最后面
//默认参数若不在最后一位,则默认参数后面的参数必须都
//有默认值
}
void main()
{
fun2();
fun2(100);
fun2(100,200);
fun2(100,200,300);
fun();
//Test1();
//Test2();
//Test3();
//Test4();
//Test5();
//short x=100000;
//short y=10000;
//int n=Test6(x,y);
//printf("%d",n);
//char szStr[100]="asdfasdfadsa";
//Test7(szStr,10);
//Test8();
//int n=100;
//int *p=&n;
//*p=200;
//int **p2=&p;
//**p2=500;
//printf("%d",n);
//int n=100;
//cout<<100<<endl<<n;
//char sz[100]="aaabbbccc";
//cout.write(sz,3);
//cout<<sz;
cout<<showbase;
cout<<hex<<100<<endl;
cout<<dec<<100<<endl;
cout<<oct<<100<<endl;
cout<<noshowbase;
cout.flush();
fflush(stdin);
int i;
char c;
char sz[10];
cin>>i>>c>>sz;
cout<<sz;
}
C/C++_lesson1~7_总结
于 2014-06-17 19:46:34 首次发布