Issue
This Content is from Stack Overflow. Question asked by Josh Reimer
So I have this code:
#include <stdio.h>
int main()
{
printf("enter charactern>>>");
char input[0];
scanf("%5s",input);
printf("%s",input);
}
that excepts 5 chars from the user. I am new to C and this one thing makes no sense to me. Why does gcc allow me to compile a program that assigns values to an array with a length of 0? Surely this is not possible? Please explain.
Solution
Your compiler ought to reject the declaration as invalid
If the expression is a constant expression, it shall have a value greater than zero. (6.7.6.2).
However, as @Joshua points out below, some compilers support this feature as an extension:
Declaring zero-length arrays is allowed in GNU C as an extension (info gcc; 6.18)
gcc -pendatic -pedantic-errors
will generate an error and only warning without -pedantic-errors
.
scanf()
and printf()
will also be undefined behavior.
This Question was asked in StackOverflow by Josh Reimer and Answered by Allan Wind It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.