C

时间:2015-10-20 05:30:24

标签: c

我在if条件中mallocing一个int和一个数组。喜欢这个

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++;

3 个答案:

答案 0 :(得分:1)

您可以将变量的声明移到函数的顶部或高于两个if语句的作用域。

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

并在第一个IpList块下设置if的值:

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

答案 1 :(得分:0)

您已在{} 1}内首先声明int connectionCount = 0;,因为它的范围仅限于if。您需要查看scope rule.

答案 2 :(得分:0)

struct sockaddr_in** IpList需要在范围({} block) that encloses the both if 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
     }
}