Shubham S. Naik - 8 months ago 36

C Question

`#include<stdio.h>`

#include<stdlib.h>

unsigned int *bin(int);

int main(void)

{

unsigned int n=0,*i=NULL;

printf("Enter no:");

scanf("%d",&n);

i=bin(n);

printf("Binary no: %d\n",*i);

return 0;

}

unsigned int *bin(int n)

{

unsigned int i=0,j=0;

static unsigned int *result=NULL;

result=(unsigned int*)malloc(1*sizeof(unsigned int));

printf("Result=%p\n",result);

j=(unsigned int)result;

for(i=(1<<31);i>0;i=(i>>1))

{

if(n & i)

{

*result=1;

result++;

}

else

{

*result=0;

result++;

}

}

result=(unsigned int*)j;

printf("Result=%p\n",result);

return result;

}

Output :

Enter no:6

Address of Result=0x2576010

Address of Result=0x2576010

Binary no: 0

The purpose of this program is to convert decimal number to binary number.The main function is calling the bin() function to convert decimal to binary.

I am confused how much space should be malloced to store 32bits of integer.And how to free memory allocated to result.Please help me out with this code.

Answer

You will need to allocate memory of 32bytes(at least) to store 1 or 0 corresponding to each bit in n considering the datatype of 1 and 0 be char. Moreover I will recommend to have int as the data type and allocate 32x4(bytes) of memory. Here is the probably your final code should look like:

```
#include<stdio.h>
#include<stdlib.h>
unsigned int *bin(int);
int main(void)
{
unsigned int n=0,*result =NULL;
printf("Enter no:");
scanf("%d",&n);
result =bin(n);
printf ("binary representation is: ");
int i;
for ( i=0;i<32;i++)
printf("%d ",result[i]);
return 0;
}
unsigned int *bin(int n)
{
unsigned int i=0;
static unsigned int *result=NULL;
result=(unsigned int*)malloc(32*sizeof(unsigned int));
printf("Result=%p\n",result);
unsigned int* j=NULL;
j=result;
for(i=(1<<31);i>0;i=(i>>1))
{
if(n & i)
{
*j=1;
j++;
}
else
{
*j=0;
j++;
}
}
return result;
}
```

Source (Stackoverflow)