0
A C problem
In the code below whenever I run the program and enter a 5-character string it raises a runtime error? The code is: #include<stdio.h> int main() { char a[5]; gets(a); printf("You entered:%s\n", a); return 0; }
1 Odpowiedź
+ 2
Strings in C are 0-terminated. That means there is an extra 0 at the end of any string so C knows where the string ends. (That's the number 0, not the character '0'). printf (and other functions) will then read the array character by character until a 0 is hit.
So you'd need an array of size 6 for a 5 character string!
It may seem odd to do it this way, but in the end every program is just numbers sitting in memory and you need some way to know when a string ends. The other choice was storing the length of the string in the string, but then you would need some extra characters aswell. The C people thought 0-termination was easier.