0

I am trying to create a function called getSortedRanks which returns an array. 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. How can I correct the way the array is being returned?

4

1 Answer 1

5

An array with automatic storage duration:

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

lives on the stack and gets destroyed after getSortedRanks finishes. 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. Using smart pointer will help you with that.

  2. Use std::vector or std::array and return by value:

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

(ordered from less to more favorable)

Sign up to request clarification or add additional context in comments.

2 Comments

I get it now. Thanks for the explanation
The array rankedMembers is not statically allocated. The reason it does not exist after the function returns is that it has automatic storage duration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.