0

In the following program, I am defining two global arrays A and B of length 3 each.

In my program, I am outputting the first A[0], A[1], A[2] and A[3].

Note . A[3] does not exist, so I expected the program to output an error or say 1e291 or something ridiculous.

But instead it outputs B[0].

Why is this?

Thanks in advance .

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <math.h>
using namespace std;

// global variables
long double A[] = {700,200,90};
long double B[] = {6000000,100000000,133510};

int main()
{	
	
	cout<<"\n"<<A[0]<<"\n";
	cout<<"\n"<<A[1]<<"\n";
	cout<<"\n"<<A[2]<<"\n";
	cout<<"\n"<<A[3]<<"\n";

	system ("PAUSE");
	return EXIT_SUCCESS;
}
4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by dusktreader
1

> Why is this?
Pure dumb luck on your part.

Your compiler just happened to make B[0] follow A[2], but there is no reason why it should have done.

0

This is an excellent object lesson! Overrunning an array will not always result in a segmentation fault. So, you can often read data beyond the end of your array without error. If you are not careful, you may end up processing this junk data, and then you will spend a good deal of pounding your head against the wall wondering why your results are bad. Bounds checking is one of the single most import skills required by good C and C++ programming!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.