I'be build this function to convert integers to binary strings
char* numberToBinary(int num){
char arr[11];
int x=1;
for(int i=0;i<10;i++){
arr[9 - i] = (num & x)?'1':'0';
x = x<<1;
}
arr[10] = '\0';
char* res = &arr[0];
printf("%s\n", res);//prints 0000000100
return res;
}
printf("%s\n", numberToBinary(4));//prints changeable binary data
The problem is inside the function the variable res
has the correct answer, but it looks like the retrieved value from the function I guess
is the location of the variable res, which has been de-located from memory.
How can I make the function numberToBinary
return a string inside of something else.