我有一些代码,我想要一个通用函数,它从主代码中获取指针并在指针地址处操作变量。问题在于指针的类型为 char、int 和 short。我希望能够在没有标志或跟踪正在传递的指针类型等的情况下执行此操作。我的猜测是可以使用指针的 typedef union ,然后该函数将采用一个 int 指针(最大数据大小三)
除了 char 指针之外,下面的排序是有效的。有更好的方法吗?
#include <stdio.h>
void pointerfunction(int *p);
int a=10;
short b=20;
char f=4;
typedef union
{
int *ptr1;
short *ptr2;
char *ptr3;
}pointers;
int main()
{
pointers mypointers;
mypointers.ptr1=&a;
pointerfunction(mypointers.ptr1);
printf("%d\n", *(mypointers.ptr1));
mypointers.ptr2=&b;
pointerfunction(mypointers.ptr1);
printf("%d\n", *(mypointers.ptr2));
mypointers.ptr3=&f;
pointerfunction(mypointers.ptr1);
printf("%d\n", *(mypointers.ptr3));
}
void pointerfunction(int *p)
{
*p=*p*10;
}
最佳答案
您使用 union 的想法是个好主意,但是您将不得不为 union 添加一个额外的成员来指示它实际上是什么类型的指针。
同一台机器上的所有指针都是相同大小的,无论它们是 int *、char * 还是 void *。
int 和 short 工作的原因是因为编译器将 int 和 short 转换为 int,所以 printf()
函数基本上认为两者相同。
首先,我将描述一个可能的实现。然而,这个特定的实现是丑陋的,并不是真正的方法,因为它有很多问题,尤其是你正在使用命令开关并真正减少 cohesion。并增加coupling .
第一次尝试会像下面这样。
#define POINTER_UNION_TYPE_CHAR 1
#define POINTER_UNION_TYPE_INT 2
#define POINTER_UNION_TYPE_SHORT 3
typedef struct {
int iType;
union {
char *pChar;
int *pInt;
short *pShort;
} u;
} Pointers;
当你使用这个结构时,你会做类似的事情:
int iValue = 1;
Pointers PointerThing;
PointerThing.u.pInt = &iValue; PointerThing.iType = POINTER_UNION_TYPE_INT;
然后在你的函数中使用这个你会做这样的事情:
void pointer_funct (Pointers *pPointers)
{
switch (pPointers->iType) {
case POINTER_UNION_TYPE_CHAR:
// do things with char pointer pPointers->u.pChar
break;
case POINTER_UNION_TYPE_INT:
// do things with char pointer pPointers->u.pInt
break;
case POINTER_UNION_TYPE_SHORT:
// do things with char pointer pPointers->u.pShort
break;
default:
break;
}
}
实现此目的的更好方法是使用单独的功能,将所有功能组合到一个功能中。所以换句话说,您将拥有三个不同的函数,每个函数都将处理特定的指针类型。这样,知道类型的功能就可以继续调用适当的函数。
另一种方法是使用一些面向对象的技术。看这个post to another though similar question .
关于c - C 中的 union 来处理将多种类型的指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11977530/