#include <iostream>
using namespace std;
void generCad(int n, char* cad){
int longi = 1, lastchar, m = n; // calculating lenght of binary string
char actual;
do{
longi++;
n /= 2;
}while(n/2 != 0);
cad = new char[longi];
lastchar = longi - 1;
do{
actual = m % 2;
cad[lastchar] = actual;
m /= 2;
lastchar--;
}while(m/2 != 0);
cout << "Cadena = " << cad;
}
Hi! I’m having a problem here because I need a function that creates a binary string for a number n. I think the process is “good” but cout doesn’t print anything, I don’t know how to fill the string I’ve created using the new operator
The code should look like this:
Note that cad is now char ** and not char *. If it is just char * then you do not get the pointer as you expect outside the function. If you do not need the string outside this function, then it may be passed as char *, but then do not forget to delete the cad before you leave the function (good habit ;-))
EDIT:
This code will probably be more readable and do the same: