C++ Dynamic Assignment Structure Pointer, question for use with other functions

Asked 2 years ago, Updated 2 years ago, 78 views

Hi, everyone. I made a simple code. I'd like to hear advice from experts who know the problem.

#include <iostream>
using namespace std;
int CountPlayer;

struct SUTDA
{
    char Name[20];
};

void Input()
{
    cout <<(Please enter up to 10 players): ";
    cin >> CountPlayer;
    SUTDA * Group = new SUTDA [CountPlayer]; // Since we assigned it to the heap, shouldn't it be possible to write it in the function below?

    for (int i = 0; i < CountPlayer; i++)
    {
        cout <<i + 1 << "Enter the name of the first player: ";
        cin >> Group[i].Name;
    }
}
void DistCard()
{
    for (int i = 0; i < 5; i++)
    {
        //SUTDA * Group = new SUTDA [CountPlayer]; //Input this and even if the input value is a number when outputting, strange characters (袴袴袴袴)袴袴袴들ᆷ) are broken
        cout << Group[i].Name; //Group identifier is not defined.
        cout << *Group[i].Name; //Group identifier is not defined.
    }
}
int main()
{
    Input();
    DistCard();
}

dynamic-allocation struct pointer function c++

2022-09-20 18:00

2 Answers

#include <iostream>
using namespace std;

struct SUTDA
{
    char Name[20];
};

SUTDA* input(const int count)
{
    SUTDA* player_group = new SUTDA[count];
    for (int i = 0; i < count; ++i) {
        cout <<i + 1 << "Enter the name of the first player: ";
        cin >> player_group[i].Name;
    }
    return player_group;
}

void dist_card(const SUTDA* player_group, const int count)
{
    for (int i = 0; i < count; ++i)
        cout << player_group[i].Name << '\n';
}

int main()
{
    cout <<(Please enter up to 10 players): ";
    int player_count{ 0 };
    cin >> player_count;

    SUTDA* players = input(player_count);

    if (players)
        dist_card(players, player_count);

    if (players)
        delete[] players;

    return 0;
}


2022-09-20 18:00

Extracted from https://m.blog.naver.com/byunhy69/140112048564,

Microsoft Visual C++ Runtime Library (with DEBUG_NEW declared) (1) (1) 0XCD, 0xCDCD, 0xCDCDCDCD

는 is 0xCDCD with cp949 encoding. In other words, it just holds the memory in new, and you can see that it's when it's not initialized.


2022-09-20 18:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.