Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need clarification about array syntax

Tags:

c++

arrays

What is the difference between declaring a 2D array in C++ like this:

int mp[3][3]={{0,2,1},
              {0,2,1},
              {1,2,0}};

And this?

int mp[3][3]={0,2,1,
              0,2,1,
              1,2,0};

Is the above an array where all 3 elements are arrays themselves while the bottom one is an array of non-array elements or are both read by the compiler as the same?

like image 801
Ishmael Avatar asked Dec 12 '25 08:12

Ishmael


2 Answers

They're equivalent. The first one is a completely braced form. When the interpretation is unambiguous (such as in the second form), the standard allows eliding the braces.

like image 153
Angew is no longer proud of SO Avatar answered Dec 13 '25 22:12

Angew is no longer proud of SO


Both are same you can access elements for matrix using following loop:

for (i=0;i<3;i++)   
     for(j=0;j<3;j++)     
        printf("%d ",mp[i][j] );

One difference in when you give braces in first case then first argument can be omitted like:

int mp[][3]={{0,2,1},
              {0,2,1},
              {1,2,0}};

But C++ compiler will give you warning: missing braces around for second type of declaration.

EDIT:
As you commented: my program was giving me different results

I have written a code. working fine on C++ (gcc-4.7.2). Check here

like image 26
Grijesh Chauhan Avatar answered Dec 13 '25 22:12

Grijesh Chauhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!