|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这段程序要求在set函数中使用new来申请空间,因此我又写了一段unset,用来释放内存。程序会出错,怎么才能在一个函数里面申请空间,在另一个函数释放内存呢?
- #include <iostream>
- #include <cstring>
- using namespace std;
- struct stringy {
- char * str;
- int ct;
- };
- void set(stringy &dst, char *src);
- void unset(stringy &src);
- void show(const stringy &src, int n = 1);
- int main()
- {
- stringy beany;
- char testing[] = "apple";
- set(beany, testing);
- show(beany);
- show(beany, 2);
- unset(beany);
- return 0;
- }
- void set(stringy &dst, char *src)
- {
- int n = strlen(src);
- dst.str = new char[n];
- strcpy(dst.str, src);
- dst.ct = n;
- }
- void unset(stringy &src)
- {
- delete[] src.str;
- }
- void show(const stringy &src, int n)
- {
- cout << src.ct << endl;
- for (int i = 0; i < n; i++) {
- cout << src.str << endl;
- }
- }
复制代码
本帖最后由 superbe 于 2020-1-13 23:00 编辑
void set(stringy &dst, char *src)
{
int n = strlen(src);
dst.str = new char[n+1]; // [n] 改成 [n+1],加 1 是保存结束符 ‘\0’ 的
strcpy(dst.str, src);
dst.ct = n;
}
|
|