Cómo devolver diferentes tipos de una sola función
Tengo el siguiente código c:
#include <stdio.h>
#include <stdlib.h>
void *func(int a) {
if (a==3) {
int a_int = 5;
int *ptr_int = &a_int;
return (void *)ptr_int;
}
else if (a==4) {
char a_char = 'b';
char *ptr_char = &a_char;
return (void *)ptr_char;
}
else {
fprintf(stderr, "return value is NULL");
return NULL;
}
}
int main (int argc, char *argv[]) {
int *ptr_int = (int *)func(3);
char *ptr_char = (char *)func(4);
fprintf(stdout, "int value = %d\n", *ptr_int);
fprintf(stdout, "char value = %c\n", *ptr_char);
return 0;
}
Pero cuando uso gcc para probar este código, tengo los siguientes resultados:
int value = 98
char value = �
root@coupure:/home/bohao/Desktop/test1375# gcc test.c -o test
root@coupure:/home/bohao/Desktop/test1375# ./test
int value = 98
char value =
root@coupure:/home/bohao/Desktop/test1375# gcc test.c -o test
root@coupure:/home/bohao/Desktop/test1375# ./test
int value = 98
char value =
root@coupure:/home/bohao/Desktop/test1375# gcc test.c -o test
root@coupure:/home/bohao/Desktop/test1375# ./test
int value = 98
char value =
root@coupure:/home/bohao/Desktop/test1375# gcc test.c -o test
root@coupure:/home/bohao/Desktop/test1375# ./test
int value = 98
char value =
root@coupure:/home/bohao/Desktop/test1375# gcc test.c -o test
root@coupure:/home/bohao/Desktop/test1375# ./test
int value = 98
char value = g
root@coupure:/home/bohao/Desktop/test1375# gcc test.c -o test
root@coupure:/home/bohao/Desktop/test1375# ./test
int value = 98
char value =
root@coupure:/home/bohao/Desktop/test1375# gcc test.c -o test
root@coupure:/home/bohao/Desktop/test1375# ./test
int value = 98
char value = !
¿Por qué tengo el98 para ptr_int y elvalor aleatorio de ptr_char?
Lo que quiero es teneruna función general quién puede devolver diferentes tipos de valores en lugar de usar dos funciones. Es eso posible ? Si es así, ¿cómo hacerlo?