开发者

"lvalue required as unary '&' operand" in accept() socket system call

开发者 https://www.devze.com 2023-03-10 04:12 出处:网络
I am writing a network program where, in the server part, I want to accept connections from multiple clients using a listening socket. So I declare an array of address structs like this:

I am writing a network program where, in the server part, I want to accept connections from multiple clients using a listening socket. So I declare an array of address structs like this:

struct sockaddr_in* client;

which I create using malloc and later on,开发者_如何学C to accept connections I type:

newsock = accept(fd_skt, (struct sockaddr *)&client[i], &(sizeof(client[i])));

and there I get "lvalue required as unary '&' operand" from the compiler. Can anyone figure out what I have done wrong?


Yes, you can't take the address of something that isn't an lvalue, that is an object with an address. The result of the sizeof operator is just a value, it isn't an object with an address.

You need to create a local variable so that you can take its address.

E.g.

socklen_t addrlen = sizeof client[i];
newsock = accept(fd_skt, (struct sockaddr *)&client[i], &addrlen));

As an aside, struct sockaddr_in* client; declares a pointer, not an array. To use client as an array you need to assign it to a dynamically allocated array at some point before the call to accept. I assume that this is what you are doing when you say "I create using malloc".

Alternatively you could actually declare client as an array.

struct sockaddr_in client[MAX_CLIENTS];


Charles' answer is correct, but one way to get around this kind of obnoxious function interface that requires a pointer to a value you plan to just throw away is to use compound literals:

newsock = accept(fd_skt, (struct sockaddr *)&client[i], (socklen_t[]){sizeof client[0]});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号