I was reading an article or post online found here: Eli Bendersky's Website : Binary Representation of Big Numbers and came across a function so I decided to test it in my IDE. The function compiles & builds but when I run the code it wants to throw an exception : write access violation.
Here is the function:
/* Note: in and out may be the same string,
it will still work OK
*/
void longdiv2(const char* in, char* out)
{
int carry = 0;
while (*in)
{
int numerator = *in++ - '0';
numerator += carry;
carry = (numerator % 2) == 0 ? 0 : 10;
*out++ = '0' + (numerator / 2);
}
*out = '\0';
}
I use it like this:
#include <iostream>
int main() {
char* value = "12345";
char* binResult = '\0';
longdiv2( value, binResult );
std::cout << *binResult << std::endl;
std::cout << "\nPress any key and enter to quit." << std::endl;
char q;
std::cin >> q;
return 0;
}
The access violation is thrown on this line:
*out++ = '0' + (numerator / 2);
The violation is stating that out
was nullptr
.
I'm running this on MS Visual Studio 2017 CE on an Intel Quad Core Extreme running Win7 Home Premium x64 - compiled and built as an x86 console application.
[Note:] I tagged this with both C & C++: I tagged it like this because the article mentioned that they written it for C, however I'm using the same function in C++.