Home > Software design >  Array printing out -858993460
Array printing out -858993460

Time:06-02

I've been trying to work out why my array is printing out -858993460 with the following code

int myInt = 0;
int myArray[10]; // I know this is undefined, but the same results occur if I put {} to initialize it

while(myInt <= 10)
{
    myArray[myInt] = myInt;
    myInt  ;
    std::cout << "Test " << myArray[myInt] << std::endl;
    std::cout << "Counter " << myInt << std::endl;
}

When print this out, myInt increments fine. However, myArray is printing out -858993460. If I insert a break point and step over the while loop with each iteration, I can see the numbers are being fed into the array, but it only prints out that random number (assuming it's a random number from the stack/heap?).

Now, if I swap around the while loop so it's now

while(myInt <= 10)
{
    myInt  ;
    myArray[myInt] = myInt;
}

it prints out the numbers correctly. I can't seem to work out what's going on here...

CodePudding user response:

Arrays in C (and by extension C ) are zero based, so an array of ten elements is indexed 0 through 9.

But your loop is trying to access elements 0 through 10. myArray[10] is actually the eleventh element of the array, which doesn't actually exist. Trying to change it is undefined behavior. Your original code was actually closer to being correct; your revised version only made it worse. What you want is:

int myInt = 0;
int myArray[10]; 
while(myInt < 10)  // <- strictly LESS THAN
{
   myArray[myInt] = myInt;
     myInt; // <- increment AFTER accessing/assigning
}

In comments, you added an additional requirement that myArray[0] should contain 1 and so forth. To get this, you need to access the element before modifying the index. You could do this with two variables:

int myInt = 0;
int myArray[10]; 
while(myInt < 10)  
{
   myArray[myInt] = myInt 1;
     myInt; 
}

You can't combine the two, unfortunately:

int myInt = 0;
int myArray[10]; 
while(myInt < 10) 
{
   myArray[myInt] =   myInt;  // <- NOPE: wrong order
}

In the revised code where you try to print out the values, you tried to access myArray[MyInt] after you changed MyInt. So you're now looking at a different element than the one you just set. No surprise it didn't print out what you want! Just move the increment to the end:

while(myInt <= 10)
{
    myArray[myInt] = myInt 1;
    std::cout << "myArray [" << myInt << "] = " << myArray[myInt] << '\n';
      myInt;  <- ALWAYS INCREMENT THE LOOP INDEX LAST
}

CodePudding user response:

You print myArray[myInt] after you have incremented myInt. That array element hasn't been initialized yet.

More over at the end myInt is 10 and your myArray only goes from 0 to 9 leading to a buffer overflow.

And last while(myInt <= 10) goes even one step further, initializing myArray[10] and printing myArray[11], both outside the array.

  • Related