我应该使用哪种类型的指针? ptrdiff_t的或无效*? [英] Which type should I use for a pointer ? ptrdiff_t or void*?

查看:127
本文介绍了我应该使用哪种类型的指针? ptrdiff_t的或无效*?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这行是定义一个指针正确的(最好的)的方式?

 的typedef ptrdiff_t的指针; //指针ptrdiff_t型。           -  要么  - 无效的typedef *指针; //指针为void *。
指针PTR =的malloc(1024);


解决方案

指针在C是类型 T * ,其中 T 的类型是指向; 无效* 是通用的指针类型。通常情况下,你令C隐式转换无效* 有用的东西,例如

 的char *缓冲区=的malloc(1024);

ptrdiff_t的是两个指针相减,例如

返回的类型

  ptrdiff_t的D = write_ptr  - 缓冲;
//现在你知道了write_ptr超出了缓冲区的开始d字节

ptrdiff_t的是一个整数类型,而不是一个指针类型;你不能使用间接运算符 * 就可以了。 (你也不能有意义使用它在一个无效* ,顺便说一句。)

假如你想一个指针存储在一个整数类型, uintptr_t形式将是适当的。

Which line is the correct (best) way for defining a pointer?

typedef ptrdiff_t pointer; // pointers are ptrdiff_t.

          -- or --

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


pointer ptr = malloc(1024);

解决方案

Pointers in C are of type T* where T is the type pointed to; void* is the generic pointer type. Usually, you let C implicitly convert void* to something useful, e.g.

char *buffer = malloc(1024);

ptrdiff_t is the type returned by the subtraction of two pointers, e.g.

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

ptrdiff_t is an integral type, not a pointer type; you cannot use the indirection operator * on it. (Nor can you meaningfully use it on a void*, by the way.)

Had you wanted to store a pointer in an integer type, uintptr_t would have been appropriate.

这篇关于我应该使用哪种类型的指针? ptrdiff_t的或无效*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆