访问头文件中的数组指针?

时间:2016-04-15 13:08:46

标签: c++ networking sdl sdl-net

尝试访问我的" clientArray"中的TCPSocket。我收到了访问冲突错误。我该如何正确访问它?

我的头文件包含TCPSocket * clientArray。

public:
TCPsocket *clientArray;
SDLNet_SocketSet aSocketSet;
bool serverOn;

它在我的构造函数中定义:

clientArray = new TCPsocket[maxsockets];
aSocketSet = SDLNet_AllocSocketSet(maxsockets);

它可以在我的另一个功能中访问(它在这里没有问题):

void ServerSocket::waitingForConnection() {

    std::cout << '\r' << flush << "Players connected: " << playersConnected        << ". Listening for connection...  ";
    TCPsocket newsocket = SDLNet_TCP_Accept(serverSocket);
    SDL_Delay(1000);

    if (!newsocket){
        //std::cout << '\r' << flush <<  "Listening for connection.  ";
        //std::cout << SDLNet_GetError() << std::endl;
    }

    else{
        std::cout << '\r' << flush <<  "Socket (client " << slotnum + 1 << ") created successfully.                           " << std::endl;
        clientArray[slotnum] = newsocket;
        int n = SDLNet_TCP_AddSocket(aSocketSet, newsocket);

        if (n < 0){
            std::cout << "Client " << slotnum + 1 << " failed to connect. " << std::endl;
        }
        else{
            char text[10];
            std::cout << "Client " << slotnum + 1 << " added to client array successfully." << std::endl;

            serverMessage(slotnum, "2 You are successfully connected to the server.");
            std::cout << "Sent connection validation to Client " << slotnum + 1 << "." << endl;

            std::cout << "Allocating player " << slotnum + 1 << " with player number ." << endl;

            serverData(slotnum, '5', slotnum+1);

            //ACCESSING IT HERE WITHOUT ISSUE
            SDLNet_TCP_Recv(clientArray[slotnum], text, 10);
            std::cout << "received text = " << text << endl;
            interpretData(text);
            slotnum++;
         }

        //SDLNet_TCP_Close(newsocket);
        //SDLNet_TCP_Close(serverSocket);
        //code here
    }
}

但是稍后当我尝试通过其他功能访问它时,我收到了访问冲突错误:

Unhandled exception at 0x00AED839 in Server.exe: 0xC0000005: Access violation reading location 0x0000000C.

我从Game的更新功能中调用有问题的功能如下:

void Game::Update(){
   while (g_playersConnected == 2)
   {
        printGrid();
        serverSocket->waitForPlayer((playerTurn-1));
        changeTurn();
        system("pause");
   }
    //cout << "Game's Update is running" << endl;
};

这是我试图访问数组的另一个函数:

void ServerSocket::waitForPlayer(int playerNum)
{
    cout << "Waiting for player " << playerNum + 1 << " (In array : " <<     playerNum << ")." << endl;
    char text[10];
    SDLNet_TCP_Recv(clientArray[playerNum], text, 10);
    std::cout << "received text = " << text << endl;
    interpretData(text);
}

我还没有设置复制构造函数或赋值运算符,而我的析构函数目前只是空块。

 ServerSocket::~ServerSocket(){}

我应该朝哪个方向解决这个问题?

一切顺利

0 个答案:

没有答案