Alfred Balle
Alfred Balle

Reputation: 1195

Pass variables to other functions in C

I have the following code in C:

int main(int argc, char **argv) {

    ...

    redisContext *c;
    redisReply *reply;

    ...

    outer_function(...)

    return 0;

}

I would like to use the Redis variables in the outer_function.

I've tried to add a struct for this before main(...):

typedef struct {
    redisReply reply;
    redisContext c;
} redisStuff;

And in main:

redisContext *c;
redisReply *reply;

redisStuff rs = { reply, c };

...

outer_function((u_char*)&rs, ...)

And finally in my outer_function:

void outer_function(u_char *args, ...) {
    redisStuff *rs = (redisStuff *) args;
    reply = redisCommand(c, "MY-REDIS-COMMAND");
    ...    
    return;
}

But it fails with:

warning: incompatible pointer to integer conversion initializing 'int' with an expression of type 'redisReply *' (aka 'struct redisReply *')

Upvotes: 1

Views: 129

Answers (2)

Ajith C Narayanan
Ajith C Narayanan

Reputation: 616

void outer_function(redisContext  *c, redisReply **reply) {
    *reply = redisCommand(c, "MY-REDIS-COMMAND");
    ...    
    return;
}

int main(int argc, char **argv) {
    ...
    redisContext *c;
    redisReply *reply;
    ...
    outer_function(c,&replay);
    return 0;
}

Upvotes: 1

hyyking
hyyking

Reputation: 39

Your struct expects values and you are passing a pointer, so the compiler can't assign a pointer as a redisContext.

typedef struct {
    redisReply reply;  // <- expects value
    redisContext c;    // <- expects value
} redisStuff;

...

redisContext *c;
redisReply *reply;

redisStuff rs = { reply, c };  // <- reply and c are pointers

Upvotes: 3

Related Questions