Reputation: 3
When I pass a struct
pointer to a function, I want the changes made to the pointer to remain after the function ends. I do not know what I have done wrong.
void webSocketHandler(struct libwebsocket_context* context)
{
/* some code */
context = libwebsocket_create_context(&info);
}
sint32 s32_WSER_Init(sint32* configDataPoolIndexes, struct libwebsocket_context* context)
{
/* some code */
webSocketHandler(configDataPoolIndexes, context);
}
The problem is that context
is not NULL
inside webSocketHandler
after creating it, but if I try to use it inside s32_WSER_Init
after calling the handler, I get NULL
.
Thanks in advance.
Upvotes: 0
Views: 215
Reputation: 62906
If you want to modify pointer to struct, you must pass pointer to pointer to struct:
void webSocketHandler(struct libwebsocket_context** context)
{
/* some code */
/* info parameter missing above? */
*context = libwebsocket_create_context(&info);
}
sint32 s32_WSER_Init(sint32* configDataPoolIndexes, struct libwebsocket_context* context)
{
/* some code */
webSocketHandler(configDataPoolIndexes, &context);
}
Your original code will modify the value of the context
parameter, which is basically a local variable in the function. C has no actual references, it has passing pointer by value, which then allows modifying the original through the pointer. If original is pointer, and you want to modify it, you need to pointer to pointer.
Upvotes: 5
Reputation: 409472
What you want is to pass the pointer by reference. Unfortunately C does not have that, but it can be emulated using pointers:
void webSocketHandler(struct libwebsocket_context** context)
{
...
*context = ...;
...
}
void some_other_function(void)
{
struct libwebsocket_context* context = NULL;
...
webSocketHandler(&context);
...
}
Upvotes: 2