This time, you need to create tow function:
void Assign(char * & str, int & length); According to the length, allocate memory to str.
void AddTwo(string & res, char & str1, char & str2); Add str1 and str2, then assign the result to the res. More importantly, you need to handle str1 and str2 to guarantee that there would not happen memory problem.
Sample input:
4
abcd
5
efghi
Sample ouput:
abcd
efghi
abcdefghi
my code
#ifndef EasyStr
#define EasyStr
#include
using std::cin;
using std::string;
void Assign(char * &, int &);
void AddTwo(string &, char * &, char * &);
#endif
#include"EasyString.hpp"
#include
#include
#include
using namespace std;
void Assign(char *& str,int& length){
str = new char[length];
}
void AddTwo(string & res , char & str1,char& str2){
res.assign(str1);
res += str2;
}
#include
#include "EasyString.hpp"
using namespace std;
int main() {
int length;
char* str0 = NULL, * str1= NULL;
cin >> length;
Assign(str0, length);
cin >> length;
Assign(str1, length);
cin >> str0 >> str1;
cout << str0 << endl << str1 << endl;
string res = "";
AddTwo(res, str0, str1);
cout << res << endl;
}
结果,评测
[1] Error : InvalidWrite
obj: /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
std::basic_istream >& std::operator>> >(std::basic_istream >&, char*)
[2] Error : InvalidWrite
obj: /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21
std::basic_istream >& std::operator>> >(std::basic_istream >&, char*)
[3] Error : InvalidRead
obj: /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
strlen
[4] Error : InvalidRead
obj: /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
strlen
[5] Error : InvalidRead
obj: /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
strlen
[6] Error : InvalidRead
obj: /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
strlen
[7] Error : Leak_DefinitelyLost
obj: /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
operator new
[8] Error : Leak_DefinitelyLost
obj: /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so
operator new