gpt4 book ai didi

c++ - 数组和指针的动态内存分配无法打印

转载 作者:行者123 更新时间:2023-11-28 04:42:28 25 4
gpt4 key购买 nike

<分区>

我尝试使用带指针的动态内存分配来打印字符数组。如果我评论一个 pf 变量工作,但是当我试图打印两个程序时停止。

这是主 CPP。

#include <iostream>
#include "ContactInfo.h"
using namespace std;

int main() {
int n = 0;
char *ph, *nm;
ContactInfo *allcontacts;

cout << "How many people you want to add to phone book? ";
cin >> n;
allcontacts = new ContactInfo[n];

for (int i=0; i < n; i++) {
cout << i + 1 << ") Name: ";
cin >> nm;
allcontacts[i].setName(nm);
cout << i + 1 << ") Phone: ";
cin >> ph;
allcontacts[i].setPhone(ph);
}

cout << setw(8) <<"Name" << setw(8) << "Phone\n";
cout << "------------------------------------------------------\n";

for (int i=0; i < n; i++){
allcontacts[i].display();
}
return 0;
}

CPP

#include "ContactInfo.h"

void ContactInfo::setName(char *n) {
name = new char[strlen(n) + 1];
strcpy(name, n);
}

void ContactInfo::setPhone(char *p) {
phone = new char[strlen(p) + 1];
strcpy(phone, p);
}

ContactInfo::ContactInfo() {
// setName("");
// setPhone("");
}

ContactInfo::ContactInfo(char *n, char *p) {
setName(n);
setPhone(p);
}

ContactInfo::~ContactInfo() {
delete [] name;
delete [] phone;
name = nullptr;
phone = nullptr;
}

const char *ContactInfo::getName() const {
return name;
}

void ContactInfo::display() const {
cout << getName();
cout << getPhoneNumber();
cout << endl;
}

const char *ContactInfo::getPhoneNumber() const {
return phone;
}

标题

 #include <iostream>
#include <cstring> // Needed for strlen and strcpy
using namespace std;

// ContactInfo class declaration.
class ContactInfo
{

private:
char *name; // The contact's name
char *phone; // The contact's phone number

public:
ContactInfo(char *, char *);
ContactInfo();
void setName(char *);
void setPhone(char *);
~ContactInfo();
const char *getName() const;
const char *getPhoneNumber() const;
void display() const;
};

输出

您想将多少人添加到电话簿? 2

1) 姓名:www

1)电话:22

进程结束,退出代码为 0

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com