Why use array size 1 instead of pointer?

后端 未结 6 821
滥情空心
滥情空心 2020-12-02 09:04

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

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

What are the advantages

6条回答
  •  没有蜡笔的小新
    2020-12-02 09:15

    They are semantically different in your example.

    char data[1] is a valid array of char with one uninitialized element allocated on the stack. You could write data[0] = 'w' and your program would be correct.

    char* data; simply declares a pointer that is invalid until initialized to point to a valid address.

提交回复
热议问题