Sreyas Sreyas - 1 month ago 13
C++ Question

C++ pointer bug pointing to all values

void main()
{

int *a, c, a1[] = { 1, 2, 3, 4, 5 }, a2[] = { 6, 7, 8, 9, 10 };
cin >> c;
if(c == 1)
a = a1;
else if(c == 2)
a = a2;
for(; *a != NULL; a++)
cout << *a << endl;

}


The output is quite obvious. When inputting
1
:

1<-inputted

1<-starting to display array elements
2

3

4

5

1<-extra element (i think it is that inputted value)


When inputting 2:

2<-inputted two (ignore)
6

7

8

9

10

1<-elements in first array is also included

2

3

4

5

2<-inputted 2 is also displaying as element


I tried my best to figure this out but no help.Can anyone point out the mistake in my code or is it a bug in C++? I tried using delete the pointer from memory but that ain't also work.The program is capturing all inputted value and when i try to point the array that is declared secondly it will point to the elements that was declared before it.

Answer

You're assuming the array's end in null... you're just printing the entire memory from whatever array you start until you find NULL through luck.

Interestingly enough, you now know the structure of the memory of your program.