为什么使用数组大小​​1,代替指针? [英] Why use array size 1 instead of pointer?

查看:135
本文介绍了为什么使用数组大小​​1,代替指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个C ++开源项目,我看到这一点。

In one C++ open source project, I see this.

struct SomeClass {
  ...
  size_t data_length;
  char data[1];
  ...
}

这样做有什么,而不是使用指针的优势是什么?

What are the advantages of doing so rather than using a pointer?

struct SomeClass {
  ...
  size_t data_length;
  char* data;
  ...
}

我能想到的唯一的事情就是与大小1阵列版本,预计不会给用户看空。还有什么?

The only thing I can think of is with the size 1 array version, users aren't expected to see NULL. Is there anything else?

推荐答案

有了这个,你不必在其他地方分配的内存,使指针指向这一点。

With this, you don't have to allocate the memory elsewhere and make the pointer point to that.


  • 没有额外的内存管理

  • 访问的内存将达到内存缓存(多)更容易

关键是要的sizeof(SomeClass的)分配比更多的内存,并进行了 SomeClass的* 点吧。那么初始内存会被你的 SomeClass的对象使用,其余的内存可以通过数据使用。也就是说,你可以说 P->数据[0] P->数据[1] 等等,直到你打的记忆结束时,你分配。

The trick is to allocate more memory than sizeof (SomeClass), and make a SomeClass* point to it. Then the initial memory will be used by your SomeClass object, and the remaining memory can be used by the data. That is, you can say p->data[0] but also p->data[1] and so on up until you hit the end of memory you allocated.

点可以进行,这在使用时导致不确定的行为,但因为你宣布你的数组只有一个元素,但访问它,如果它含有较多的。但真正的编译器做让这种与预期的意义,因为C ++有没有替代语法制定这些手段(C99已,这就是所谓的柔性数组成员那里)。

Points can be made that this use results in undefined behavior though, because you declared your array to only have one element, but access it as if it contained more. But real compilers do allow this with the expected meaning because C++ has no alternative syntax to formulate these means (C99 has, it's called "flexible array member" there).

这篇关于为什么使用数组大小​​1,代替指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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