LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Find the Error · Question 6

Error (C17): initialising a variable length array Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Compiled as C17, why is this program rejected?

main.c
#include <stdio.h>

int main(void) {
    int n = 5;
    int counts[n] = {0};
    printf("%d\n", counts[0]);
    return 0;
}
  • A n must be unsigned
  • B counts is a variable length array, and a VLA cannot have an initializer (C23 allows only = {}) Correct
  • C {0} needs five zeros
  • D There is no bug
Correct Answer: Option B

A VLA's size is known only at run time, so a compile-time initializer list cannot be checked against it. Zero it with a loop or memset(), use a constant size, or in C23 write int counts[n] = {};.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links