C struct hack at work

后端 未结 4 1449
野趣味
野趣味 2020-11-28 06:39

Is this how one can use the the \"extra\" memory allocated while using the C struct hack?

Questions:

I have a C struct hack implementation below. My questio

4条回答
  •  猫巷女王i
    2020-11-28 07:02

    Ever since I read this article (http://blogs.msdn.com/b/oldnewthing/archive/2004/08/26/220873.aspx), I've liked to use the struct hack like so:

      #include
      #include
    
      int main()
      {
    
          struct mystruct {
    
              int len;
              char chararray[1];
          };
    
          int number_of_elements = 10;
    
          struct mystruct *ptr = malloc(offsetof(struct mystruct, chararray[number_of_elements]));
          ptr->len = number_of_elements;
    
          for (i = 0; i < number_of_elements; ++i) {
            ptr->chararray[i] = 'a' + i;
          }
    
      }
    

    I find that not having to remember whether 1 needs to be subtracted (or added or whatever) is nice. This also has the bonus of working in situations where 0 is used in the array definition, which not all compilers support but some do. If the allocation is based on offsetof() you don't need to worry about that possible detail making your math wrong.

    It also works without change is the struct is a C99 flexible array member.

提交回复
热议问题