1

它是指向对象的数组的基本程序。

#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<< 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;
};

还有一个警告(这个警告不是问题)

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删除警告,但这个词无法识别。

4

4 回答 4

2

cptr是一个字符指针数组。并且数组的大小固定为10:

city *cptr[10];

这使得0to9作为数组的有效索引。但是您的 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 it
delete[]s;
于 2011-12-20T07:02:36.617 回答
1

如果您输入了多个9(我相信)条目,这意味着您继续过去,您会覆盖内存,因为您会在循环中不断增加索引并且您没有检查是否到达数组末尾,因此您将继续。

于 2011-12-20T07:04:28.307 回答
1

你真的讨厌这个例子中的内存 :) 一旦你分配了内存,你必须释放它。

  1. 您需要声明析构函数,您将在其中释放 ; 指向的内存city::name
  2. city::getname()中,您需要释放内存两次:
    • 在重新分配name指针之前;
    • 在方法返回之前;
  3. 最后,您需要cptr在从main().
于 2011-12-20T07:17:15.477 回答
0

替换i<=ni<n...

for (int i=1;i<=n;i++)
于 2011-12-20T07:00:44.643 回答