函数返回错误的指针

问题描述

所以我有一个数组,其中每个元素都包含指向另一个包含对象的数组的指针。看起来像

Person thePeople[25];
Person *referenceToThePeople[25];

for (int i = 0; i < count; i++) {
        referenceToThePeople[i] = &thePeople[i];
    }

我要求用户输入一个字符串,然后使用指针数组找到一个指针,该指针指向一个对象,该对象的成员字符串与该函数的用户字符串相匹配:

Person* findAPerson(Person** personArray,int arraySize,string userPerson) {
    for (int i = 0; i < arraySize; i++) {
        if (userPerson == (*personArray)[i].name) {
            return personArray[i];
        }
    }
    return nullptr;
}

这是询问用户名的代码。


do {
        cout << "Enter a name: ";
        getline(cin,userName);

        userPerson = findAPerson(referenceToThePeople,count,userName);

        if (userPerson != nullptr) {
            displayAPerson(cout,userPerson);
        }
        else {
            cout << "No person found" << endl;
        }

    }while(userName != "no more");

这很好,问题是当我使用选择排序按年龄对人进行排序时。

void sortPersonArrayByAge(Person** personArray,int arraySize) {
    int min;
    for (int i = 0; i < arraySize - 1; i++) {
        min = i;
        for (int j = i + 1; j < arraySize; j++) {
            if ((*personArray)[j].age < (*personArray)[min].age) {
                min = j;
                swap((personArray[min]),(personArray[i]));
            }
        }
    }
}

在此处切换地址的指针似乎仍指向其原始地址。例如,“ John”和“ Joe”将在选择排序中交换,但是当我键入“ John”时,出现的名称是“ Joe”。有什么原因吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...