gpt4 book ai didi

c - 如何声明指向不同数据类型的指针,但它们将占用相同的内存空间

转载 作者:行者123 更新时间:2023-11-30 21:08:57 25 4
gpt4 key购买 nike

这是我的代码

int main()
{
char *pchar;
short *pshort;
int *pint;
long *plong;
float *pfloat;
double *pdouble;

pchar = pshort = pint = plong = pfloat = pdouble;
printf("sizeof *pchar is = %u\n",sizeof(pchar));
printf("sizeof *pshort is = %u\n",sizeof(pshort));
printf("sizeof *pint is = %u\n",sizeof(pint));
printf("sizeof *plong is = %u\n",sizeof(plong));
printf("sizeof *pfloat is = %u\n",sizeof(pfloat));
printf("sizeof *pdouble is = %u\n",sizeof(pdouble));

return 0;
}

我希望这些指针变量中的每一个都指向不同的数据类型,但它们将在内存中占用相同的空间量。我怎样才能做到这一点?

最佳答案

创建一个通用指针。

When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer.

这个link有一个例子。

关于c - 如何声明指向不同数据类型的指针,但它们将占用相同的内存空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com