简体   繁体   中英

Why is this printing memory addresses instead of values

Here is my driver

int square[2][2] = {
    {1,2},
    {3,4}
};

matrixMulti(square, 2);

Here is my function

void matrixMulti(const int a[][2], const int rows) {

    int b[2][2];

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                b[i][j] += a[i][k] * a[k][j];
            }
        }
    }

    cout << "new matrix " << endl;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            cout << b[i][j] << " ";
        }
        cout << endl;
    }
}

The output is:

new matrix
-858993453 -858993450
-858993445 -858993438

I am confused as to why it is printing the memory addresses rather then the values stored in them and what can be done to get it to print the values rather than the memory address.

You wrote:

int b[2][2];

and then

b[i][j] += ...

Where did you initialize b?

int b[2][2] = {};

or

int b[2][2] = {0,0};

Should do the job.

Garbage values are being printed, not the address of the array. Here is why. In this snippet of code

void matrixMulti(const int a[][2], const int rows) {

    int b[2][2];

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                b[i][j] += a[i][k] * a[k][j];
            }
        }
    }

You allocated space for int b[2][2] , but you do not initialize it to a value. This would be fine except in the for-loop body. b[i][j] += a[i][k] * a[k][j]; <=> b[i][j] = b[i][j] + a[i][k] * a[k][j]; you are referencing the value of b[i][j] before it is initialized. In other words you say b[i][j] is equal to b[i][j] + a[i][k] * a[k][j] , but you can't do this as, the value of b[i][j] is unknown.

The solution to this is to initialize int b[2][2] = {{0,0},{0,0}};

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