0

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

}


msy02
  • 11
  • Having access to a debugger like gdb or the one in Visual Studio should help you answer the question in the title. – drescherjm May 24 '21 at 23:52
  • `hammingCode[j] = -1;` is `j` always less than m+n? – drescherjm May 24 '21 at 23:54
  • messageBits size is 20, if user enters m >20, code might crash – Rushikesh Talokar May 24 '21 at 23:59
  • Anytime you have a for loop starting at 1 and `<=` length in C/C++, it smells very bad. `for(int i{1};i<=m;i++){ std::cin>>messageBits[i];` is almost certainly not correct because it skips the 0th entry and probably reads beyond the array. – Michael Dorgan May 25 '21 at 00:34
  • For integral powers of 2, you shouldn't use `pow(2, r)`. `pow()` is a math function working with floating point. Just use `1 << r`. That's more precisely (and probably breathtakingly faster). – Scheff's Cat May 25 '21 at 05:43

0 Answers0