Hi, I am learning C++ from jumping into C++. There is a practice problem in pointer chapter "Write a program that lets users keep track of the last time they talked to each of their friends.
Users should be able to add new friends (as many as they want!) and st
ore the number of days ago that they last talked to each friend. Let users update this value (but don't let them put in
bogus numbers like negative values). Make it possible to display the list sorted by the names of
the friends of by how recently it was since they talked to each friend.
"
but the program is crashing sometimes giving segmantation fault. most of the time.also it can realocate memory only for the first time.it dont realocate if I again call for more.I am also confused about how and where should I use delete.
my code is
Code:
#include <iostream>
#include <string>
using namespace std;
void allocatemore(int *&p,string *&s,int x,int n)
{
string *s1=new string[x+n];
int *p1=new int[x+n];
for(int i=0;i<x;++i)
{
*(s1+i)=*(s+i);
*(p1+i)=*(p+i);
}
for(int i=x;i<n;++i)
{
cout<<"Enter the of your new friends\n";
cin>>*(s1+i);
cout<<"Enter the last meeting date of your friend\n";
cin>>*(p1+i);
}
p=p1;
s=s1;
}
int main()
{
cout<<"Intially how many friends do you want?\n";
int x; cin>>x;
string *names=new string[x];
int *days=new int[x];
for(int i=0;i<x;++i)
{
cout<<"Enter the name of your friend\n";
cin>>names[i];
cout<<"Enter the last date of meeting\n";
cin>>days[i];
}
while(1)
{
cout<<"If you want to add more friends,type more\n"
<<"If you want to view the last date of meeting of any friend type friend\n"
<<"And q to quit\n";
string s;
cin>>s;
if(s=="more")
{
cout<<"How many more friends do you want?\n";
int n;
cin>>n;
allocatemore(days,names,x,n);
x+=n;
}
if(s=="friend")
{
cout<<"What is the name of your friend?\n";
string sfr;
cin>>sfr;
for(int i=0;i<x;++i)
{
if(names[i]==sfr)
{
cout<<"You have meet "<<sfr<<" "<<days[i]<<"days ago.\nDo you want to update the date?y or N\n";
char con; cin>>con;
if(con!='n'||con!='N')
{
int j; cin>>j;
days[i]=j;
}
break;
}
}
}
if(s=="q")
break;
}
}