Strange array behviour

Hi,

I am puzzled with the strange behavior of my code below. The code has an apparent error but the results are correct. I am trying to put two arrays (chara and shuffled) into a third array join. The first 10 elements of 'join' should have the elements of 'chara' and the second half should have the elements of 'shuffled'.

You will note that in the second For loop, I am using 'chara' instead of 'shuffled' but when I print the contents of 'join' I am getting the correct numbers.
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,

On the other hand if I replace 'chara' with 'shuffled' in the second For loop, I am getting incorrect results.
1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,


Why is this happening?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <stdio.h>

using namespace std;

int main()
{
    int chara[]={1,2,3,4,5,6,7,8,9,10};
    int shuffled[]={11,12,13,14,15,16,17,18,19,20};
    int join[20];
    int c;
    int n;
    int len;
    int c2;
    int filled=0;
    len=sizeof(join)/sizeof(int);


    for(n=0;n<len/2;n++)
    {
        join[n]=chara[n];
    }

 
    for(n=(len/2);n<len;n++)
    {
        join[n]=chara[n];  //Strange
    }


    for(c=0;c<len;c++)
    {
        cout<<join[c]<<", ";
    }


    return 0;
}
In the second for loop n goes from 10 to 19 so chara[n] is out of bounds. It will just read whatever is being store after the chara array in memory.

My guess is that the shuffled array is being stored after the chara array so chara[10] gives shuffled[0], chara[11] gives shuffled[1], and so on. This is just a coincidence though and nothing you should rely on. I ran your code and for me the result is different.
Topic archived. No new replies allowed.