Como retornar tipos diferentes de uma única função
Eu tenho o seguinte 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;
}
Mas quando eu uso o gcc para testar esse código, tenho os seguintes 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 que eu tenho o98 para ptr_int e ovalor aleatório de ptr_char?
O que eu quero é teruma função geral quem pode retornar tipos diferentes de valores em vez de usar duas funções. Isso é possível ? Se for o caso, como fazer ?