Home > Enterprise >  How can I export answer that I expected?
How can I export answer that I expected?

Time:06-21

#include <stdio.h>

int main()
{   
    int tarr[3][4];
    //this for loop is for making 2d array

    for (int i = 0; i < 3; i  )
    {
        for (int j = 0; j < 4; j  )
        {
            tarr[i][j] = (i  ) * (j  );
        }
    }

    // this for loop is for exporting 2d array
    for (int i = 0; i < 3; i  )
    { 
        for (int j = 0; j < 4; j  )
        {
            printf("%d ", tarr[i][j]);
        }

        printf("\n");
    }

    return 0;
}

expected answer:

1 2 3 4 
2 4 6 8 
3 6 9 12 

actual exported answer:

194 0 -566790131 22024 
-1681794240 0 0 0 
-566790208 22024 -566790672 2 

My expectation was to export as I expected but the weird numbers were exported and I cannot understand where those numbers are from. I want to know where those numbers are from and what should I do for exporting my expected numbers.

CodePudding user response:

Code eventually attempts to access data outside arrays bounds leading to undefined behavior (UB).

for( int j = 0; j<4; j  ) {
    // On the first iteration, i,j is 0,0
    // On the next iteration, i,j is 1,2
    tarr[i][j]= (i  )*(j  );
}

Do not increment: (i )*(j ). Instead, simply add 1.

for( int j = 0; j<4; j  ) {
    // On the first iteration, i,j is 0,0
    // On the next iteration, i,j is 0,1
    tarr[i][j]= (i 1) * (j 1);
}
  • Related