Why does the code do not give error?

Why does this code do not giver error, the size of century is 3 elements, still it holds for elelments={'h','e','l','\0'}????

1
2
3
4
5
6
7
8
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char century[3]="hel";
getch();
}
It should give an error, and it would with a modern compiler. Your old compiler (I'm guessing Borland from last century) is probably too permissive
Please update your C++ compiler.
Visual C++ Express would be a nice start. It's free and powerful IDE, and contains a modern C++ compiler.
Why does this code do not giver error, the size of century is 3 elements, still it holds for elelments
This is actually least of your concerns.
#include<iostream.h> and void main() should be your main problem
My School curriculum is based on Turbo c++ Version 3.0 which dates back to 1990-1992. I cant help it. So..........
is Borland still in busness?
if you use Orwell Dev C++, you will get following message:
[Error] initializer-string for array of chars is too long [-fpermissive]

What is actually happening (probably) is that century is not actually 'holding' four elements, but you are writing four elements with the assignment ( century[3] = "hel"; ).

the string "hel" has a hidden null terminator at the end, which via this assignment ends up writing to an address which it shouldn't. Since there's no bounds checking on arrays, it works. But your stepping on memory which you shouldn't be.
Topic archived. No new replies allowed.