我有以下 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;
}
但是当我使用 gcc 测试这段代码时,我得到以下结果:
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 = !
为什么我有 ptr_int 的 98 和 ptr_char 的随机值?
我想要的是一个通用函数,它可以返回不同类型的值,而不是使用两个函数。那可能吗 ?如果是这样,该怎么做?
最佳答案
我所看到的问题是,您试图从函数(作用域)返回
局部变量的地址,并试图从调用者访问返回的内存。在调用者中,内存无效,任何使用都将导致 undefined behavior .
解决方案:您需要为要返回
的指针(malloc()
/calloc()
)使用动态内存分配从功能。这将解决这里的问题,因为动态分配的内存的生命周期是直到手动 free()
-d 或直到程序终止,以较早者为准。
话虽如此,这种方法并不好。如果您只想返回多种类型中的一种,请选择包含所有类型成员的 struct
并使用标志来标记类型。填充相应的成员变量,设置标志并返回
结构变量。
更好的是,您实际上可以使用union
作为结构的成员,因为您一次只需要一个类型。有关工作代码,请参阅 the other answer通过@pmg。
关于c - 如何从单个函数返回不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37433525/