Why is my C++ Hamming code crashing after the first output?

72 Views Asked by At

I just started learning c++. I have started to write code for creating a hamming code but I am still in the very beginning of writing the code. I tested out what I have so far and my code crashes after asking the user for "Enter the number of bits:". I would appreciate some help as to why it is doing this:) (PS. this code is still incomplete)

#include <iostream> //standard library
#include <string>
#include <iomanip>
#include <math.h>

void messageIntoHammingCode(int , int* , int*);

int main() {
    int messageBits[20]; //this is an array containing data bits
    int m; //number of data bits
    int r{0}; //number of redundant bits
    
    //Number of bits in the user input
    std::cout<<"Enter the number of bits: ";
    std::cin>>m;
    
    //Calculate Number of redundant bits r using formula 2^r<m+r+1
    while(pow(2,r) < m+r+1){
        r++;
    }
    
    //Length of the output message
    int hammingCode[r+m];
    /*Redundant Bits are added as follow:
    r1 at position 2^0
    r2 at 2^1
    r3 at 2^2, etc.*/
    //Initiliaze redudant bits to -1
    for(int i{0};i<=r+m;i++){
        int j = pow(2,i);
        hammingCode[j] = -1;
    }
    
    //User inputs data bit
    std::cout<<"Enter the Data Bits: ";
    for(int i{1};i<=m;i++){
        std::cin>>messageBits[i];
        //place the bit into the hamming cde
        messageIntoHammingCode(i,hammingCode, messageBits);
    }

    std::cout<<hammingCode;
    
}
void messageIntoHammingCode(int i, int hammingCode[], int messageBits[20]){
    //PLace the given code in the rest of the bits
    if(hammingCode[i]!=-1){
           hammingCode[i] = messageBits[i]; 
    }

}


0

There are 0 best solutions below