in this code i am trying to return a function that can add ctx.a to passed argument x
the intended answer is 4 but when running this code prints 6.
what is going wrong here?
i have tried this code
#include <stdio.h>
typedef struct {
int a;
} ctx_t;
typedef void(*with_ctx)(int);
with_ctx create_handler(ctx_t ctx) {
void handler(int x) {
printf("%dn", ctx.a + x);
}
return handler;
}
int main() {
ctx_t ctx = { .a = 1 };
with_ctx handler = create_handler(ctx);
handler(3);
return 0;
}
New contributor
neo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.