Austin Heath
Austin Heath

Reputation: 75

Trying to access object in an array of objects but only one object is saved

I'm trying to implement the GoBackN ARQ for a class. I'm attempting to read a file, break it up into packets of 30 characters and then store the packets in an array of packets. All of these packets are objects of the class packet.

Currently, this code compiles and runs however when I access the array of packets, at index 0 of the array I receive the last and most recent packet. When I attempt to access index 1, I expected a different packet, however, the packets are the same in all of the indices.

Why is the data in all of my packets the same?

int numPackets = 0;
packet *packetArray[30];

void addPacket(packet *p)
{
    for (int i = 0; i < 30; i++)
    {
        if (packetArray[i])
        {
            continue;
        }
        else
        {
            packetArray[i] = p;
            numPackets++;
            break;
        }
    }
}

int main(int argumentCount, char *argumentVariables[]) {

    char buffer[1024];

    std::ifstream infile (argumentVariables[1], std::ifstream::binary);
    infile.seekg (0, infile.end);
    int lengthOfFile = infile.tellg();
    infile.seekg (0, infile.beg);

    int iterator = 0;
    while(1)
    {
        if (lengthOfFile > 30)
        {
            bzero(buffer, 1024);
            infile.read(buffer, 30);
            lengthOfFile -= 30;
            addPacket(new packet(1, iterator, strlen(buffer), buffer));
            iterator++;
        }
        else
        {
            bzero(buffer, 1024);
            infile.read(buffer, 30);
            addPacket(new packet(1, iterator, strlen(buffer), buffer));
            break;
        }
    }

    packet * sendpckt = packetArray[0];
    sendpckt->serialize(sendPayload);
    printf("%s\n", sendPayload);

    infile.close();

    return 0;
}

Constructor code of the class packet.

packet::packet(int t, int s, int l, char * d){
    type = t;
    seqnum = s;
    length = l;
    data = d;
}

Upvotes: 1

Views: 61

Answers (1)

lewohart
lewohart

Reputation: 97

Can you show the constructor code of class "packet". First I think you must add a '\0' in the end of buffer after the "infile.read(buffer, 30)", second check if you are copying the buffer or only the address of the buffer to a "packet" member.

Upvotes: 0

Related Questions