ProgrammingVery hard
Which code creates a flexible structure holding n ints after a header, with a single allocation and correct size?
- A. struct S *s = malloc(sizeof(struct S *) + n);
- B. struct S s = malloc(n * sizeof(int));
- C. struct S *s = malloc(sizeof *s + n * sizeof s->data[0]); where data is the last member declared as int data[];
- 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
- A tail-insertion function takes a pointer to the head pointer, so it can work on an empty list. Which loop finds the link to change?
- A queue with head and tail pointers is emptied by dequeuing its only node. What must the dequeue do to keep the queue correct?
- A recursive function removes all nodes equal to x from a singly linked list and returns the new head. Which return statement is the right…
- A program creates an array of 10^6 pointers and then one malloc block per pointer, with 10^6 frees at the end. What is the total number of…
- What is the effect of realloc(p, 0) when p came from malloc, in the C standard's terms?
- A function returns a pointer to a dynamically allocated copy of its argument string. Which signature is the most correct for the caller's…