读书人

一个关于molloc/free和new/delete的有

发布时间: 2013-07-08 14:13:00 作者: rapoo

一个关于molloc/free和new/delete的问题:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main ()
{
char *a;
a = (char *)malloc( 100*sizeof(char) );
cout << "Please input your string: " << endl;
cin >> a;
cout << "The string is: " << endl;
cout << a << endl;
free (a);

char *b;
b = new char(100);
cout << "Please input your string: " << endl;
cin >> b;
cout << "The string is: " << endl;
cout << b << endl;
delete b;

return 0;
} C++ C语言
[解决办法]
b = new char[100]
......
delete[] b;

按你的意思,以上2行要改一下。剩下的地方,你自己上机试试吧。
[解决办法]

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main ()
{
char *a = (char *)malloc(100 * sizeof(char));
cout << "Please input your string: " << endl;
cin >> a;
cout << "The string is: " << endl;
cout << a << endl;
free(a);

char *b = new char[100]; //[中括]是量;(小括)是初始值
cout << "Please input your string: " << endl;
cin >> b;
cout << "The string is: " << endl;
cout << b << endl;
delete[] b; //b 量
system("pause");
return 0;
}

读书人网 >C++ Builder

热点推荐