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
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” witha[i]then index the “column” with[j], whencea[i][j].So, why does your code compile? Because the
,is an operator in C. The evaluation ofa,bis effectively the evaluation of expressiona, thenb, returning the result of evaluating b. Hence you’re actually printinga[j]here, which is anint[], 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 likefor, 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.