HelloWorld之内存分配版本

看看如下的helloWorld:

版本1:

#include<iostream>
#include<time.h>
using namespace std;
void add(char* szChar)
{
 char str[20]="hello,world";
 strcpy(szChar,str);
 //szChar="hello,world";
}
void main()
{
  char szChar[1024];
  memset(szChar,0,sizeof(szChar));
  add(szChar);
  cout<<szChar<<endl;
  getchar();
}

版本2:

#include<time.h>
using namespace std;
char* add()
{
 char* str = new char[20];
  char a[20] = "hello world";
 strcpy(szChar,&a);
 return str;
}
void main()
{
  char *str = add();
  cout<<str<<endl;
delete str;
  getchar();
}

//版本3:初学者易错版本

//函数里的变量是临时的,内存会在函数结束时释放,

//new 申请的内存是要程序员自己释放的,而你这个用的是函数内部变量,函数结束,内存自动释放

//可以看下C/C++高质量编程,比较简捷很多问题也都提到了

char* add()
{
 char str[22];
 memset(str,0,sizeof(str));
 //str="hello,world";
 strcpy(str,"hello,world");
 return str;
}

原文地址:https://www.cnblogs.com/xianqingzh/p/1558965.html