ProgrammingVery hard

Which code creates a flexible structure holding n ints after a header, with a single allocation and correct size?

  1. A. struct S *s = malloc(sizeof(struct S *) + n);
  2. B. struct S s = malloc(n * sizeof(int));
  3. C. struct S *s = malloc(sizeof *s + n * sizeof s->data[0]); where data is the last member declared as int data[];
  4. D. struct S *s = malloc(sizeof(struct S) * n * sizeof(int) + 1);

Correct answer: C. struct S *s = malloc(sizeof *s + n * sizeof s->data[0]); where data is the last member declared as int data[];

A flexible array member at the end of the struct is sized by the extra allocation. sizeof *s plus n elements gives exactly the needed bytes.

More C Programming questions

Exams that ask this topic