简体   繁体   English

C函数返回错误的数组

[英]c++ function returning incorrect array

I am trying to create a function called getSortedRanks which returns an array. 我正在尝试创建一个名为getSortedRanks的函数,该函数返回一个数组。 I copied the format for returning arrays from this question Return array in a function but the array is not being returned correctly. 在函数中从该问题“ 返回数组”复制了用于返回数组的格式,但是未正确返回该数组。

#include <stdlib.h>
#include <stdio.h>
#define familyMembers 4

int *getSortedRanks()
{
    int rankedMembers[familyMembers] = {3,4,2,1};
    return rankedMembers;
}

int main()
{
    int *sortedRanks = getSortedRanks();

    //print the returned array
    for(int i = 0; i < familyMembers; i ++)
    {
        cout << "ranked member is " << sortedRanks[i] << endl;
    }

    return 0;
}

When I run this the output is: 当我运行此输出是:

ranked member is 3
ranked member is 0
ranked member is 0
ranked member is 2686744

The first element of the array sortedRanks is always correct but the others are not. 数组sortedRanks的第一个元素始终正确,而其他元素sortedRanks正确。 How can I correct the way the array is being returned? 如何纠正返回数组的方式?

An array with automatic storage duration: 具有自动存储持续时间的阵列:

int rankedMembers[familyMembers] = {3, 4, 2, 1};

lives on the stack and gets destroyed after getSortedRanks finishes. 存在于堆栈中,并在getSortedRanks完成后被getSortedRanks The returned pointer is invalidated. 返回的指针无效。 Dereferencing it leads to undefined behavior . 取消引用它会导致未定义的行为

You'll either want to: 您要么想要:

  1. Allocate the array dynamically (on the heap), as you'll manage its lifetime: 动态(在堆上)分配数组,因为您将管理其生命周期:

     int *getSortedRanks() { return new int[familyMembers]{3, 4, 2, 1}; } 

    Don't forget to delete [] it after the use. 使用后不要忘记delete [] Using smart pointer will help you with that. 使用智能指针将帮助您。

  2. Use std::vector or std::array and return by value: 使用std::vectorstd::array并按值返回:

     std::array<int, familyMembers> getSortedRanks() { return {3, 4, 2, 1}; } 

(ordered from less to more favorable) (从少到多排序)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM