I swear I really am a decent programmer but my adventures in C programming after programming in Java for years are driving me mad.
I'm trying to fill a two dimensional char array with a set of IP Address/Port pairs. I'm reading them in from a file. They are being pulled out of the file correctly, and, should be being placed into the array correctly. The problem is that for some reason when the second set is being placed into the array it's overwriting the first set and I cannot for the life of me figure out why.
The first line of the file is the number of IP Address/Port pairs in the file (I call them tuples). The following lines are the IP addresses and ports separated by a space.
Here is the code:
//read the top line with the number of items
fgets(line, sizeof line, fp);
numLines = atoi(line);
printf("%s %d\n","numLines:",numLines);
char* tuples[numLines][2];
char* rawLines[numLines];
//read each line and put it into array
for(currentLine=0; currentLine<numLines; currentLine++){
if(fgets(line, sizeof line, fp) == NULL){
perror("fgets");
return -1;
}
printf("%s %d \n","curentLine: ",currentLine);
char* port;
tuples[currentLine][0] = strtok(line, " ");
printf("%s %s \n", "IP Address: ", tuples[currentLine][0]);
//rawLines[currentLine] = line;
port = strtok(NULL, " ");
size_t ln = strlen(port) - 1;
if (port[ln] == '\n')
port[ln] = '\0';
tuples[currentLine][1]=port;
printf("%s %s\n","port: ", tuples[currentLine][1]);
}
//list created and stored in tuples
//now that list is created choose a random server from the file and strip the value chosen from the list
//choose random server
srand (time(NULL));
//randomServer = rand()%numLines;
randomServer = 0;
printf("%s %d\n", "randomServer: ", randomServer);
//connect to random server pulled
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
//setup client socket
printf("%s %s \n", "Setting up connection to: ", tuples[randomeServer][0]);
printf("%s %s \n", "Setting up connection on port: ", tuples[randomServer][1]);
Here is the output I get:
numLines: 2
curentLine: 0
IP Address: 127.0.0.1
port: 3761
curentLine: 1
IP Address: 192.168.0.1
port: 3762
randomServer: 0
Setting up connection to: 192.168.0.1
Setting up connection on port: 1
What I expect to get is: Setting up connection to: 127.0.0.1 Setting up connection on port: 3761
If I only have one line in the file then I get the expected values.
Thank you in advance.