简体   繁体   中英

Strange C++ matrix multiplication/initialization

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;
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM