G
Guest
The output is:
1234
After getline: 1234
After renew: 1234
After retnp: ÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝG
After getp: ÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝG
-----What happen after renew/retnp call?-------
Why not return a true array?
-----The code is as followed-------------------
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void print(char *,const char *);
void renew(char *);
void retnp(char *);
char* getp(char *);
int main(int argc, char* argv[])
{
char *p = new char[5];
cin.getline(p,5);
print(p,"getline");
renew(p);
print(p,"renew");
retnp(p);
print(p,"retnp");
char * p1;
p1 = getp(p);
print(p1,"getp");
return 0;
}
//print
void print(char *p,const char *st)
{
cout<<"After "<<st<<": "<<p<<endl;
}
//renew
void renew(char *p)
{
char *p1 = new char[strlen(p)+1];
strcpy(p1,p);
delete [] p;
p = new char[10];
strcpy(p,p1);
}
//retnp
void retnp(char *p)
{
char *p1 = new char[strlen(p)+1];
strcpy(p1,p);
delete [] p;
p = p1;
p1 = NULL;
delete p1;
}
//getp
char* getp(char *p)
{
char *p1 = new char[strlen(p)+1];
strcpy(p1,p);
return p1;
}
1234
After getline: 1234
After renew: 1234
After retnp: ÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝG
After getp: ÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝÝG
-----What happen after renew/retnp call?-------
Why not return a true array?
-----The code is as followed-------------------
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void print(char *,const char *);
void renew(char *);
void retnp(char *);
char* getp(char *);
int main(int argc, char* argv[])
{
char *p = new char[5];
cin.getline(p,5);
print(p,"getline");
renew(p);
print(p,"renew");
retnp(p);
print(p,"retnp");
char * p1;
p1 = getp(p);
print(p1,"getp");
return 0;
}
void print(char *p,const char *st)
{
cout<<"After "<<st<<": "<<p<<endl;
}
//renew
void renew(char *p)
{
char *p1 = new char[strlen(p)+1];
strcpy(p1,p);
delete [] p;
p = new char[10];
strcpy(p,p1);
}
//retnp
void retnp(char *p)
{
char *p1 = new char[strlen(p)+1];
strcpy(p1,p);
delete [] p;
p = p1;
p1 = NULL;
delete p1;
}
//getp
char* getp(char *p)
{
char *p1 = new char[strlen(p)+1];
strcpy(p1,p);
return p1;
}