array bound index validation

as in c++ there is no such array bound index validation, on what does the arbitrary result depends on ?

for eg:
int a[3]={4,8,0};
if i print :
cout <<a[6];
it prints some result, on what does this result depends on ?
It generally depends on the memory contents directly after the array. If that address isn't mapped, the application will crash.
But it's undefined behavior, so there's no guarantee as to what will happen. The compiler might just as well decide to use a default value like 0 if it sees that it's an out-of-bound access or trigger a runtime error.
It will be totaly random.

cout <<a[6]; read memory after the array. May be an other variable ...

You could use vector to avoid this problem.
If you have an array...

E.g.
 
int a[3];


... then &a[0] will return a pointer to the memory location of where the array starts.

Increasing the offset (the number between the square brackets) will simply increment the pointer by the size of the array data type (int his case int) by how ever many times you specify. So &a[6] will return a pointer to 6 memory locations past the start of 'a'. In this case, since the array 'a' only contains 3 memory locations, &a[6] will point to a position in memory that has absolutely nothing to do with the array and so the returned result could be anything since this adjacent memory could be being used for anything. Perhaps it is being used to store a string. maybe another array of ints. There is no way for you to know.

When you say...

 
int n = a[6];


... memory is being read from the memory position &a[6] until an ints worth of data has been read, and it is then being interpreted as a meaningless integer.
Last edited on
thank you for all the replies..got it now .!
btw one more thing if its possible..
is there any way i can specify the compiler which memory addresses to use for the data type.
eg:
let us suppose i want to assign int b[9]; a memory location that starts from a[3], i.e the memory just after the end of a[];

just asking if its possible or not ?
I think the answer is no, you can't, but variables created on the stack are usually created in a consistent order (anyone know if this is mandated in the specification?). Anyway, try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void test()
{
   int b[3];
   int a[3];
   a[0] = 1;
   a[1] = 2;
   a[2] = 3;
   b[0] = 4;
   b[1] = 5;
   b[2] = 6;

   cout << "&a[0] = " <<  &a[0] << endl;
   cout << "&b[0] = " <<  &b[0] << endl;
   for (int i = 0; i <= 7; i++)
   {
		cout << a[i] << endl;
   }
}

What you can do is:
1
2
3
int mem[12];
int* a = mem;
int* b = mem + 3;

This way you have b right after a if you considers a as an array of 3 int
@aquaz: clever!
You can also use templates to get that information from an array (but not a pointer, mind you).

http://www.cplusplus.com/forum/general/19458/#msg101474
http://www.cplusplus.com/forum/general/33669/

Hope this helps.
Topic archived. No new replies allowed.