Shubham S. Naik Shubham S. Naik - 24 days ago 7
C Question

Why the pointer from called function doesn't return the value to calling function?

#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.

Logic of Code :- Let us take unsigned integer (32 bit), which consist of 0-31 bits. To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.

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;
}
Comments