2015-10-20 84 views
1

我正在mallocing一個int和一個數組,如果條件。像這樣範圍分辨率在C

if(type == 1){ 
     int connectionCount = 0; 
     struct sockaddr_in** IpList = malloc(sizeof(struct sockaddr_in*)*256); 
     for (int i = 0; i <256; ++i) 
     { 
      IpList[i] = malloc(sizeof(struct sockaddr_in) * 256); 
     } 
    } 

後來我想,如果

if(type == 1){ 
    sockClient = accept(sockServer, (struct sockaddr*)&remoteaddr, &addrlen); 
     if(sockClient < 0){ 
      perror("Accept failed: "); 
     }else{ 
      FD_SET(sockClient, &master); 
      if(sockClient > fdmax){ 
      fdmax = sockClient; 
     } 
     IpList[connectionCount] = remoteaddr; 
     connectionCount++; 

     //send list to all connections in list 
     }//end of else 
    } 

訪問內的另一個相同的變量,我得到以下編譯錯誤

:108:13: warning: unused variable 'connectionCount' [-Wunused-variable] 
     int connectionCount = 0; 
      ^
:184:49: error: use of undeclared identifier 'connectionCount' 
          for (int i = 0; i < connectionCount; ++i) 
               ^
:186:62: error: use of undeclared identifier 'IpList' 
           struct sockaddr_in tempSock = IpList[i]; 
                  ^
:220:33: error: use of undeclared identifier 'IpList' 
           IpList[connectionCount] = remoteaddr; 
           ^
:220:40: error: use of undeclared identifier 'connectionCount' 
           IpList[connectionCount] = remoteaddr; 
            ^
:221:33: error: use of undeclared identifier 'connectionCount' 
           connectionCount++; 
+0

而你的問題。你可以嘗試來聲明變量'揮發性int'擺脫這些錯誤的 – ForceBru

+2

你需要回去學習basi C的cs,特別是範圍規則和可變的生命期。簡單的答案是'IpList'和'connectionCount'是它們在其中定義的塊內部的本地,任何其他'IpList'或'connectionCount'變量都是不同的變量。 –

回答

1

可以移動變量的聲明到函數的頂部或高於兩個if語句的範圍。

int connectionCount = 0; 
struct sockaddr_in** IpList = NULL; 

和設置的IpList值第一if塊下:

IpList = malloc(sizeof(struct sockaddr_in*)*256); 
0

你已經宣佈在裏面int connectionCount = 0;第一,如果,這樣你就可以不被外部訪問它if,因爲它的範圍僅限於僅限第一個if。你需要看scope rule.

0

struct sockaddr_in** IpList需要在一個範圍({} block) that encloses the both如果statements. In C the scoping rules are easy: a declaration is visible inside the outmost {}`塊中聲明,所有包含塊例:

{ 
    int x; 
    if(condition) { 
     x = ...; // x is referencing the enclosing block/scope 
    } else { 
     int y; // y is only available in this block/scope 
     x = ...; // x is referencing the enclosing block/scope 
    } 
} 

注意,你可以在任何時候重寫訪問一個名字用更緊密的聲明陰影它:?

{ 
    int x; 
    if(condition) { 
     x = ...; // x is referencing the enclosing block/scope 
    } else { 
     int x; // This x shadows the outer x 
     x = ...; // x is referencing this enclosing block/scope 
    } 
}