gpt4 book ai didi

c - 我应该使用哪种类型的指针? ptrdiff_t 还是 void*?

转载 作者:太空宇宙 更新时间:2023-11-04 00:17:07 28 4
gpt4 key购买 nike

哪一行是定义指针​​的正确(最佳)方法?

typedef ptrdiff_t pointer; // pointers are ptrdiff_t.

-- or --

typedef void* pointer; // pointers are void*.


pointer ptr = malloc(1024);

最佳答案

C 中的指针是 T* 类型,其中 T 是指向的类型; void* 是通用指针类型。通常,您让 C 将 void* 隐式转换为有用的东西,例如

char *buffer = malloc(1024);

ptrdiff_t 是两个指针相减返回的类型,例如

ptrdiff_t d = write_ptr - buffer;
// now you know the write_ptr is d bytes beyond the start of the buffer

ptrdiff_t是整型,不是指针类型;您不能在其上使用间接运算符 *。 (顺便说一句,你也不能在 void* 上有意义地使用它。)

如果您想以整数类型存储指针,uintptr_t 会很合适。

关于c - 我应该使用哪种类型的指针? ptrdiff_t 还是 void*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10108605/

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