it’s a basic program for array of pointer to objects.
#include <iostream>
using namespace std;
class city
{
protected:
char *name;
int len;
public:
city()
{
len=0;
name= new char[len+1];
}
void getname(void)
{
char *s;
s= new char[30];
cout<< "enter city name";
cin >> s;
len= strlen(s);
name = new char[len+1];
strcpy(name, s);
}
void printname(void)
{
cout<< name <<"\n";
}
};
compiler says problem is in the “cout<< name <<“\n”;”
int main()
{
city *cptr[10];
int n=1;
int option;
do
{
cptr[n]= new city;
cptr[n]->getname();
n++;
cout<< "continue? yes=1, no=0. select now?";
cin>> option;
}
while(option);
cout<< endl<< endl;
for (int i=1;i<=n;i++)
{
cptr[i]-> printname();
}
cin.ignore();
getchar();
return 0;
};
There’s also a warning(this warning is not an issue)
warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files\microsoft visual studio 10.0\vc\include\string.h(105) : see declaration of 'strcpy'
I tried strcpy_s to remove the warning, but the word is unrecognized.
cptris an array of character pointers. And the size of the array is fixed to 10:This makes
0to9as the valid index into the array. But your do-while loop does not perform this check. If the user keeps continuing by inputting1you’ll go and write beyond the array.And array index in C++ start with
0and not1soshould be:
And
should be
Also consider using
strncpyin place ofstrcpy.Also you are leaking memory by not freeing the memory allocated to
s. You need to free it by callingdelete: