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;
}

Recommended Answers

All 3 Replies

> 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.

The way your compiler put things together, B is after A. You overrun A onto the start of B.

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.