我正在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++;
而你的問題。你可以嘗試來聲明變量'揮發性int'擺脫這些錯誤的 – ForceBru
你需要回去學習basi C的cs,特別是範圍規則和可變的生命期。簡單的答案是'IpList'和'connectionCount'是它們在其中定義的塊內部的本地,任何其他'IpList'或'connectionCount'變量都是不同的變量。 –