return a struct pointer from a function

June Lin 41 Reputation points
2022-06-02T11:43:20.397+00:00
struct DataInformation
{
    char *Name;
    int Number;
};

DataInformation *GetDataList()
{
    int count = 3;
    DataInformation *data;
    data = (DataInformation *)malloc(count * sizeof(DataInformation));

    data[0].Name = (char *)malloc(sizeof(char) * 6);
    data[0].Name = (char *)"first";
    data[0].Number = 1;
    data[1].Name = (char *)malloc(sizeof(char) * 7);
    data[1].Name = (char *)"second";
    data[1].Number = 2;

    for (int i = 0; i < 2; i++)
    {
        std::cout << "function: " << data[i].Name << std::endl;
    }

    return data;
}

int main(int argc, char const *argv[])
{
    DataInformation * list = GetDataList();    

    return 0;
}

Does anyone can help me, why it cannot work?

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,765 questions
{count} votes

Accepted answer
  1. YujianYao-MSFT 4,291 Reputation points Microsoft Vendor
    2022-06-03T02:39:35.74+00:00

    Hi @June Lin ,

    I suggest you describe the problem you're having in detail.

    I modified your code and now the program runs without any errors and warnings. You could also find that the list has been assigned a value through the for loop.

    Is this the result you want?

    #include<iostream>  
      
    struct DataInformation  
    {  
        char* Name;  
        int Number;  
    };  
    DataInformation* data;  
    DataInformation* GetDataList()  
    {  
          
        int count = 3;  
          
        data = new DataInformation[count];  
      
          
        data[0].Name = (char*)"first";  
        data[0].Number = 1;  
          
        data[1].Name = (char*)"second";  
        data[1].Number = 2;  
      
       
      
        return data;  
    }  
      
    int main(int argc, char const* argv[])  
    {  
        GetDataList();  
        DataInformation* list = data;  
        for (int i = 0; i < 2; i++)  
        {  
            std::cout << "function: " << list[i].Name << std::endl;  
        }  
        free(list);  
         
        return 0;  
    }  
    

    208017-result.png

    Best regards,

    Elya


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.