Wie man verschiedene Typen von einer einzelnen Funktion zurückgibt
Ich habe den folgenden C-Code:
#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;
}
Aber wenn ich diesen Code mit gcc teste, erhalte ich die folgenden Ergebnisse:
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 = !
Warum habe ich das 98 für ptr_int und das Random Value von ptr_char?
Was ich will ist, @ zu hab eine allgemeine Funktion who kann verschiedene Arten von Werten zurückgeben, anstatt zwei Funktionen zu verwenden. Ist das möglich ? Wenn ja, wie geht das?