我發誓我真的是一個體面的程序員,但是在Java編程多年後,我在C編程中的冒險讓我很生氣。二維字符陣列問題
我想用一組IP地址/端口對填充二維字符數組。我正在從文件中讀取它們。他們正在被正確地拉出文件,並且應該被正確地放入數組中。問題是,由於某種原因,當第二組被放入數組時,它將覆蓋第一組,並且我不能爲了我的生活找出原因。
該文件的第一行是文件中的IP地址/端口對數(我稱之爲元組)。以下行是由空格分隔的IP地址和端口。
下面是代碼:
//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]);
這裏是輸出我得到:
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
我希望得到的是: 連接設置到:127.0.0.1 建立連接在端口上:3761
如果我只在文件中有一行,那麼我會得到期望的值。
預先感謝您。
看起來像是指派一個指向內容稍後改變的數組的指針的典型症狀。除此之外:1. **感謝您使用'fgets()'而不是死腦筋的'scanf()'(由於某種原因每個人都喜歡(ab)使用),2.但是爲什麼'printf (「%s%d \ n」,「numLines:」,numLines);'?更可讀的版本是'printf(「numLines:%d \ n」,numLines);'。此外,'strtol()'優於'atoi()'。 – 2013-10-09 19:40:38
不應該是'sizeof(line)'? – John
@John不,爲什麼? 'line'是一個對象,而不是一個類型。 – 2013-10-09 19:42:52