C函数参数设置全局变量的值?

时间:2015-10-17 08:37:29

标签: c function pointers arguments return-value

我正在创建可以向函数传递的参数变量声明值的函数。

例如,来自我的server.c文件:

int sfd;    //socket file descriptor
int listenv;  //if listen
struct sockaddr_in serverAddress;   //server address

int main(int argc, char * argv[]) { //argv[0] == server //argv[1] == port number

    listenv = setServer(argv[1],serverAddress,sfd);
            //int port = ntohs(serverAddress.sin_port);
            printf("sfd = %d port = %d\n", sfd, ntohs(serverAddress.sin_port));
    while (listenv == 0) {
    }
}

从我的serverAPI.h文件:

int setServer (char * portn,struct sockaddr_in saddr,int sfd) {

    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);
    saddr.sin_port = (int)htons(atoi(portn));


    sfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sfd < 0)
        error("ERROR opening socket");
    printf("Successfully opened socket sfd = %d\n",sfd);

    if (bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr)) == -1 )
        error("ERROR on binding");
    printf("Successfully Binded on port %d\n", ntohs(saddr.sin_port));//show correct port number

    int listenv;
    if((listenv = listen(sfd,5)) < 0)
        error("ERROR on listening");
    //print message to show connection has been made
    printf("Ready and Listening...");

    return (listenv);
}

这就是我的......

我希望通过'setServer'函数传递变量(即ServerAddress和sfd),函数会声明这些值,但它没有......

因此setServer函数内的返回值为:

serverAddress.sin_port = 12345
sfd = 3
listenv = 0

从主要:

serverAddress.sin_port = 0
sfd = 0
listenv = 0

因为它已被列为全球。

我需要将什么设置为setServer的参数,以便它可以设置全局变量的值?

1 个答案:

答案 0 :(得分:2)

当C通过按值复制传递参数时,在修改sfdsaddr时,只修改参数本身,即传递参数的副本。您需要传递指针以实际修改变量。像这样声明setServer

int setServer (char * portn, struct sockaddr_in* saddr, int* sfd);

添加解除引用操作符:

saddr->sin_family = AF_INET;
saddr->sin_addr.s_addr = htonl(INADDR_ANY);
saddr->sin_port = (int)htons(atoi(portn));


*sfd = socket(AF_INET, SOCK_STREAM, 0);
if (*sfd < 0)
    error("ERROR opening socket");
printf("Successfully opened socket sfd = %d\n",*sfd);

if (bind(*sfd, (struct sockaddr *) saddr, sizeof(*saddr)) == -1 )
    error("ERROR on binding");
printf("Successfully Binded on port %d\n", ntohs(saddr->sin_port));//show correct port number

int listenv;
if((listenv = listen(*sfd,5)) < 0)
    error("ERROR on listening");
//print message to show connection has been made
printf("Ready and Listening...");

return (listenv);

使用指针

调用setServer
listenv = setServer(argv[1],&serverAddress,&sfd);