Strange C++ matrix multiplication/initialization -


i'm using cygwin, windows vista, norton anti-virus (someone asked me before). asked question strange c++ behavior no 1 answer. here's another. simple matrix multiplication exercise. form below gives strange (and wrong) results:

#include <iostream> #include <string> #include<cmath>  using namespace std;  int main(int argc, char* argv[]) {    int a[3][3]={{1,5,0},{7,1,2},{0,0,1}};    int b[3][3]={{-2,0,1},{1,0,0},{4,1,0}};    int d[3][3];    (int i=0;i<3;i++)    {       for(int j=0;j<3;j++)       {          (int k=0;k<3;k++)          {             d[i][j]+=a[i][k]*b[k][j];           }       }    }     (int i=0;i<3;i++)    {       for(int j=0;j<3;j++)       {          cout<<d[i][j]<<"\n";       }}    return 0; } 

but small change gives correct results: (all i've done move initialized matrices outside main() ).

#include <iostream> #include <string> #include<cmath>  using namespace std;  int a[3][3]={{1,5,0},{7,1,2},{0,0,1}}; int b[3][3]={{-2,0,1},{1,0,0},{4,1,0}}; int d[3][3];  int main(int argc, char* argv[]) {    (int i=0;i<3;i++)    {       for(int j=0;j<3;j++)       {          (int k=0;k<3;k++)          {             d[i][j]+=a[i][k]*b[k][j];           }       }    }     (int i=0;i<3;i++)    {       for(int j=0;j<3;j++)       {          cout<<d[i][j]<<"\n";       }}    return 0; } 

you forgot initialize array d 0 in first case. automatically done when array global, not when local (simplified, explains behavior).


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -