它是指向对象的指针数组的基本程序。#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"; }};编译器说问题出在“cout 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;};还有一个警告(此警告不是问题)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'我尝试通过strcpy_s删除警告,但该单词无法识别。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 cptr是字符指针数组。并且数组的大小固定为10:city *cptr[10];这使得0到9作为数组的有效索引。但是您的do-while循环不会执行此检查。如果用户继续通过输入1继续操作,那么您将继续写数组之外的内容。C++中的数组索引以0而不是1开头,因此for (int i=1;i<=n;i++)应该:for (int i=0;i<n;i++)和int n=1;应该int n=0;还可以考虑使用strncpy代替strcpy.另外,您通过不释放分配给s的内存来泄漏内存。您需要通过调用delete释放它:char *s;s= new char[30];// use itdelete[]s; (adsbygoogle = window.adsbygoogle || []).push({});