0

This code is to convert from input string to binary. But the pointer tempPointer in dataToCode() function is crashing the application. Please guide. Thank you.

int main(void)
{
string text;
    cout << " Enter the text/code you want to convert: ";
    cin >> text;
dataToCode(text); 
}

string* asciiToBinary(string input) {

    string binaryArray[5];

    for (int i = 0; i < input.length(); i++) {

         binaryArray[i] = bitset<8>(input[i]).to_string();
         //cout << binaryArray[i] << endl;
    }
    string* tempPointer = binaryArray;
    for (int i = 0; i < input.length(); i++) {

        //cout << *(tempPointer + i);
    }
    return tempPointer;

}

void dataToCode(string input) {

    string binaryCode[5];

    string* tempPointer = asciiToBinary(input);

    for (int i = 0; i < input.length(); i++) {
        //binaryCode[i] = *(tempPointer + i);
        //cout << binaryCode[i] << endl;
        cout << *(tempPointer + i);
    }

}
haris
  • 149
  • 1
  • 14
  • Well you need to validate your pointer by using `if (tempPointer)`. That would be a good thing to do. tempPointer is pointing to an array of 5 element but you are looping on the size of input. Are you sure that `input.length()` is not bigger than 5? – Ceros Apr 13 '16 at 19:10
  • @Ceros `tempPointer` will never be a valid pointer. – NathanOliver Apr 13 '16 at 19:11
  • @Nathan, what should I do? – haris Apr 13 '16 at 19:13
  • @Ceros, I only put in string of 5 character long. It works in asciiToBinary function but the pointer does not pass too dataToCode function. – haris Apr 13 '16 at 19:15
  • Well since you know wha the size of the array should be just use a `std::array` and you can return that from the function. – NathanOliver Apr 13 '16 at 19:18
  • @Peter, you are creating your array in asciiToBinary as a local variable. As soon as you exit this function, this array does not exist anymore. – Ceros Apr 13 '16 at 19:19
  • The above link by Nathan helped me solve it. string* asciiToBinary(string input) { string* tempPointer = new string[5]; for (int i = 0; i < input.length(); i++) { tempPointer[i] = bitset<8>(input[i]).to_string(); //cout << binaryArray[i] << endl; } return tempPointer; } – haris Apr 13 '16 at 19:20

0 Answers0