Why use array size 1 instead of pointer?

后端 未结 6 819
滥情空心
滥情空心 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:25

    This is usually a quick(and dirty?) way of avoiding multiple memory allocations and deallocations, though it's more C stylish than C++.

    That is, instead of this:

    struct SomeClass *foo = malloc(sizeof *foo);
    foo->data = malloc(data_len);
    memcpy(foo->data,data,data_len);
    
    ....
    free(foo->data);
    free(foo);
    

    You do something like this:

    struct SomeClass *foo = malloc(sizeof *foo + data_len);
    memcpy(foo->data,data,data_len);
    
    ...
    free(foo);
    

    In addition to saving (de)allocation calls, this can also save a bit of memory as there's no space for a pointer and you could even use space that otherwise could have been struct padding.

提交回复
热议问题