Błażej
Błażej

Reputation: 3635

Decimal itself converts to hexadecimal

I have small issue. I create 2D int array. When I cout it I get hexadecimals numbers insted of decimals. I'm using Dev C++.

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    const int max=9;
    int ar[max][max]={
        {0,6,0,0,2,0,0,4,0},
        {5,0,0,3,0,0,0,0,0},
        {0,8,0,0,1,0,0,0,0},
        {6,0,0,0,0,7,0,0,0},
        {0,3,7,0,0,0,2,8,0},
        {0,2,0,8,0,0,0,3,0},
        {0,0,0,0,0,0,0,0,0},
        {7,0,0,4,0,0,0,0,1},
        {0,0,0,0,6,0,0,2,0}};

    for (int i=0;i<max;i++){
        for(int j=0;j<max;j++){
            cout<<ar[i,j]<<" ";
        }
        cout<<"\n";
    }

    system("pause");
    return 0;
}

In return I get this http://www.dropmocks.com/mf8wl

Upvotes: 1

Views: 399

Answers (5)

Adam Wright
Adam Wright

Reputation: 49386

That's because you've fallen into the cunning trap of operator ,!

First of all, C doesn't have multi-dimensional arrays as a primitive. As you've declared here, a 2D array is just "an array of arrays". Therefore, it makes no sense to access an array with a[i,j]. You should first get the "row" with a[i] then index the "column" with [j], whence a[i][j].

So, why does your code compile? Because the , is an operator in C. The evaluation of a,b is effectively the evaluation of expression a, then b, returning the result of evaluating b. Hence you're actually printing a[j] here, which is an int[], printed in hex as the address of the array.

Why have an operator , at all, you ask? Other than to be confusing, it's mostly for constructs like for, where you might want multiple expressions in an initialiser or incrementation construct, i.e. for (j = 0, i = 0; i + j < k; i++, j += 2) or similar.

Upvotes: 9

Kevin
Kevin

Reputation: 76254

cout<<ar[i,j]<<" ";

Change this line to:

cout<<ar[i][j]<<" ";

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191058

You want to do

cout<<ar[i][j]<<" ";

http://ideone.com/G5n4Z with GNU says its undefined behavior.

Upvotes: 0

Jeff Foster
Jeff Foster

Reputation: 44746

cout << ar[i,j] << " ";

This should read

cout << ar[i][j] << " ";

The comma operator , does (from here)

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

So this is printing out ar[j] (after evaluating i and discarding the result) which is a pointer and hence hexadecimal.

Upvotes: 4

Luchian Grigore
Luchian Grigore

Reputation: 258678

The C++ syntax for accessing array members is:

ar[i][j]

You coming from a Pascal background? :P

Upvotes: 2

Related Questions