C++ 结构指针

标签 c++ pointers struct

我的代码不工作。我有一个错误 -fpermissive(“从‘int’到‘persona*’的无效转换 [-fpermessive]”)。 你能帮助我吗?这是我的第一个真正的程序,对于错误和糟糕的英语感到抱歉。

    #include <iostream>

using namespace std;

struct persona
{
    char nome[20];
    unsigned int eta;
    unsigned int altezza;
    unsigned int peso;
};

int totale = 0;
struct persona prs[100];

void leggere_dati(persona* prs)
{
    cout << "Persona numero: " << (totale + 1) << endl;
    cout << "Nome: " << prs->nome << endl;
    cout << "Eta': " << prs->eta << endl;
    cout << "Altezza: " << prs->altezza << endl;
    cout << "Peso: " << prs->peso << endl;
    cout << "-----------------------------------------------\n";
}

void inserire_dati(persona* prs)
{
    cout << "Nome? ";
    cin >> prs -> nome;
    cout << "\nEta'? ";
    cin >> prs -> eta;
    cout << "\nAltezza? ";
    cin >> prs -> altezza;
    cout << "\nPeso? ";
    cin >> prs -> peso;
}

int main()
{
     int risposte = 0;
    char risp = 0;

        do{
        inserire_dati(totale);
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
        if (risp == 'S')
    {
        risposte += 1;
        totale++;
        continue;
    }
    } while (risp == 's' || risp == 'S');

    if (risp == 'n' || risp == 'N')
    {
        for (totale = 0; totale <=  risposte; totale++)
            leggere_dati(totale);
    }
}

最佳答案

您正在打电话:

 inserire_dati(totale);

定义为:

void inserire_dati(persona* prs);

虽然总计是:

int totale = 0;

这是明显的错误。但是背景问题是您没有persona 结构的对象来读取数据。据我了解您的代码,该行应该是:

inserire_dati(&prs[totale]);

您在该函数中接受了指向 persona 结构的指针,这是正确的,因为您要修改该结构的内容。 totale 保留最后一个位置(我认为,但你应该无条件地增加 totale)。为了获得指向您使用 & 的结构的指针,前面是对象,即 prs[totale]。由于 vector 的名称是指向其开头的指针,因此 prs + totale 也是可以接受的。在这种情况下,您将使用可读性较差的指针算法。

此外,我不明白 main() 的最后一部分。

最后,如果您真的使用 C++,则没有真正的理由使用 char[] 而不是 string

完整的 main() 变成:

int main()
{
    char risp = 0;

    do {
        inserire_dati(&prs[totale]);
        ++totale;
        cout << "Inserire un'altra persona? (S/N)" << endl;
        cin >> risp;
    } while (risp == 's' || risp == 'S');

    for(int i = 0; i < totale; ++i) {
         leggere_dati(&prs[totale]);
    }
}

但是,好吧,更进一步,我看到您正在使用 totale 作为全局变量。我会将 totaleprs 包装在一个完整的结构中。

struct personas {
    static const int Max = 100;
    struct prs[Max];
    int totale;
};

还有其他一些changes which you can find in IDEOne .

希望这对您有所帮助。

关于C++ 结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967703/

相关文章:

c++ - 在 Rcpp 中实现应用功能

c++ - "invalid pure specifier"当我的意思是没有纯说明符时?

c++ - 传递派生类指针 C++ 时的运行时错误

c - 如何避免变量自动分配到我的指针指向的内存单元的情况?

c - 在 C 中使用结构并返回二维数组

c++ - HTTP multipart/form-data 发送一个字符串数组

c++ - Boost::asio、共享内存和进程间通信

c - c 中指向字符串的指针数组中的字符数组

一次复制 8 个字节的结构

c - 将文本文件读取到双向链表