Strange C++ matrix multiplication/initialization

时间:2016-02-03 03:32:50

标签: c++ matrix

I'm using Cygwin, Windows Vista, Norton anti-virus (someone asked me about this before). I previously asked a question about strange C++ behavior that no one could answer. Here's another. Simple matrix multiplication exercise. This 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];
   for (int i=0;i<3;i++)
   {
      for(int j=0;j<3;j++)
      {
         for (int k=0;k<3;k++)
         {
            D[i][j]+=A[i][k]*B[k][j];

         }
      }
   }

   for (int i=0;i<3;i++)
   {
      for(int j=0;j<3;j++)
      {
         cout<<D[i][j]<<"\n";
      }}
   return 0;
}

BUT a very small change gives correct results: (all I've done is move the 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[])
{
   for (int i=0;i<3;i++)
   {
      for(int j=0;j<3;j++)
      {
         for (int k=0;k<3;k++)
         {
            D[i][j]+=A[i][k]*B[k][j];

         }
      }
   }

   for (int i=0;i<3;i++)
   {
      for(int j=0;j<3;j++)
      {
         cout<<D[i][j]<<"\n";
      }}
   return 0;
}

1 个答案:

答案 0 :(得分:5)

You forgot to initialize the array D to 0 in your first case. This is automatically done when the array is global, but not when it is local (simplified, but explains the behavior).