I have this struct defined:
typedef struct Socket_s
{
...
SocketConnectFunc Connect;
...
}Socket;
where SocketConnectFunc is defined as:
typedef Socket_Return (*SocketConnectFunc) (void * self);
When initialising a Socket structure, I call this:
void Init(Socket * sock)
{
sock = (Socket *)malloc(sizof(Socket));
if(sock)
sock->Connect = SocketConnect;
}
But then, when I attempt to call sock->Connect()
I get segmentation开发者_StackOverflow fault, and the function isn't even entered. Is there a problem in the way I assigned sock->Connect
?
NB. Socket_Return is an enum (typedef enum {SUCCESS,FAIL} Socket_Return
)
You need to pass the address of the pointer. Passing just the pointer you can't change it in the caller
void Init(Socket ** sock) {
*sock = malloc(sizeof **sock); /* don't cast the return value of malloc! */
if (*sock)
(*sock)->connect = SocketConnect;
}
And call it like so
struct Socket_s *mysock;
Init(&mysock);
I would write it like this:
Socket * CreateSocket() {
Socket * sock = (Socket *) malloc( sizeof( Socket ) );
if ( sock ) {
sock->Connect = SocketConnect;
}
return sock;
}
精彩评论