News for hackers. Stuff that matters.
Re:Tell HN: C Experts Panel – Ask us anything about C by scythe on Tuesday April 14, 2020 @12:29PM (#22867953)
>There have been no proposals to add new array types and it doesn't seem likely at the core language level.

One alternative to adding types is to allow enforcing consistency in some structs with the trailing array:

    struct my_obj {
      const size_t n;
      //other variables
      char text[n];
    };
where for simplicity you might only allow the first member to act as a length (and it must of course be constant). The point is that then the initializer:

    struct my_obj b = {.n = 5};
should produce an object of the right size. For heap allocation you could use something like:

    void * vmalloc(size_t base, size_t var, size_t cnt) {
      void *ret = malloc(base + var * cnt);
      if (!ret) return ret;
      * (size_t *) ret = cnt;
      return ret;
    }
Re:Tell HN: C Experts Panel – Ask us anything about C by saagarjha on Tuesday April 14, 2020 @07:26PM (#22872683)
What should happen if you reassign the object?
Re:Tell HN: C Experts Panel – Ask us anything about C by scythe on Wednesday April 15, 2020 @12:54AM (#22874647)
What do you mean "reassign"?

You can't reassign the length variable since it's marked `const`. You should see something like "warning: assignment discards `const` qualifier from pointer target type" if you pass it to `realloc`, which tells you that you're breaking consistency (I guess this might be UB). You could write `vrealloc` to allow resizing such structs, which would probably be called like:

    my_obj *tmp = vrealloc(obj, sizeof(obj), sizeof(obj->text), obj->n, newsize);
Re:Tell HN: C Experts Panel – Ask us anything about C by saagarjha on Wednesday April 15, 2020 @01:20AM (#22874782)
What would you do with the old text? Delete it?
Re:Tell HN: C Experts Panel – Ask us anything about C by scythe on Wednesday April 15, 2020 @08:03AM (#22876727)
Could you please be more specific about what you're trying to say? I have no idea what your actual objection is.
Re:Tell HN: C Experts Panel – Ask us anything about C by jschwartzi on Tuesday April 14, 2020 @02:01PM (#22869246)
I would love this.