c - 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 program convert decimal number binary number.the main function calling bin() function convert decimal binary.

logic of code :- let take unsigned integer (32 bit), consist of 0-31 bits. print binary representation of unsigned integer, start 31th bit, check whether 31th bit on or off, if on print “1” else print “0”. check whether 30th bit on or off, if on print “1” else print “0”, bits 31 0, binary representation of number.

i confused how space should malloced store 32bits of integer.and how free memory allocated result.please me out code.

you need allocate memory of 32bytes(at least) store 1 or 0 corresponding each bit in n considering datatype of 1 , 0 char. recommend have int data type , allocate 32x4(bytes) of memory. here final code should 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;   ( i=0;i<32;i++)     printf("%d ",result[i]);   free(result);   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

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -