简体   繁体   中英

Why does this program print -58684322800B5FD80?

#include "stdafx.h"
#include <iostream>
using namespace std;


int main()
{
        int x[3];
        int i;
        int pause;
        for (i = 0; x[i] < 10; i++); {
                x[i] *= x[i];
                cout << x[i];
        }
        cout << x;
        cin >> pause;

    return 0;
}

What did I do wrong?

Shouldn't it print:

16
25
36
{16, 25, 36}

I'm quite new to C++ so I may have misused a loop.

Thanks

You need to initialise the array contents. The compiler does not do that for you.

Even then, you'll need to initialise them to something other than zero, else the loop will never terminate.

Your algorithm is also vulnerable to your writing outside the bounds of the array. Are you sure that i will never be greater than 2? I'm not.

Finally your cout call will output the address of the first element of x due to pointer decay. To output actual elements use x[i] or similar.

Reading/Writing to an Un-initialized variable will produce an Undefined Behavior.

In your case you should initialize the array before using it.

int x[3] = {4, 5, 6};

Also that is not how to iterate over the array elements:

 for (i = 0; x[i] < 10; i++);{}

Above you should check whether i is less than the size of the array (3) not the value 10.

Also remove the semicolon ; Because in your code no iteration will occur and the body below for loop will be executed once.

So your code will look like:

    int x[3] = {4, 5, 6};

    for (int i = 0; i < 3; i++) {
        x[i] *= x[i];
        std::cout << x[i];
    }

   std::cin.get();
  • As I guess above from what output you wanted and what the loop for does I filled the array with the values: 4, 5, 6 ;

  • Also you shouldn't print the elements of the array that way:

    std::cout << x;

Above it will only print the address of first element x[0] because the name of an array will decay to pointer to its first element (element 0).

std::cout << *x; // will print 16 (4 * 4). Which is the first element.

To print or assign all the elements use iteration:

for(int i(0); i < 3; i++)
    std::cout << x[i] << ", ";

You have to initialize your array. Default initialization is not performed for local variables. That is why it is printing garbage value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM