phillis
phillis

Reputation: 33

Error in my code - Boolean Truth Table

I am currently working on a program that prints a 5 variable truth table. I am using a 2d array. My code currently produces the table, but says it is corrupt and "the stack around the variable "table" was corrupted. Any help?

#include <iostream>
using namespace std;

int main() {
    bool table[5][32];

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 5; j++) {
            table[i][j] = ((i >> j)& 1);
        }
    }

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 5; j++) {
            cout << table[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

This is homework, so I would like to understand it, not just have an answer.

Upvotes: 2

Views: 151

Answers (2)

Digital_Reality
Digital_Reality

Reputation: 4738

There is attempt to read out of bound values from array.

If you need 5x32 matrix Use code below:

    for (int i = 0; i < 5; i++) {          // 32-> 5
        for (int j = 0; j < 32; j++) {     // 5->32

If you need 32x5 matrix then replace code below:

    bool table[32][5];        //it was table[5][32];

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

The index is wrong. Only table[0] to table[4] are available, so accessing table[5] to table[31] is illegal.

Try this:

#include <iostream>
using namespace std;

int main() {
    bool table[32][5]; // swap 32 and 5

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 5; j++) {
            table[i][j] = ((i >> j)& 1);
        }
    }

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 5; j++) {
            cout << table[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Upvotes: 1

Related Questions