Ali Abdulhussein Ali Abdulhussein - 23 days ago 5
C Question

Function return Char array C

I try to return char array from function. I am new in C and try to learn function return value.
This is my code:

int main()
{
unsigned int nr;
unsigned int mask=32;

char *outString;

printf("Enter Nr:\n");
scanf("%u",&nr);

outString = getBinary(nr,mask);
printf("%s",outString);
//getch();
return 0;
}

char * getBinary(int nr,int mask)
{
static char outPut[sizeof(mask)]="";
while(mask>0)
{
if((nr&mask)==0)
{
strcat(outPut,"0");
}
else
{
strcat(outPut,"1");
}
mask=mask>>1;
}

//printf("%s",outPut);
return outPut;
}


I can't make program work! With two error on function call.

Answer

you can change program like following:

#include <stdio.h>
#include <string.h>
char * getBinary(int nr,int mask); // add function header, it necessary to avoid compilation error 
//otherwise you can move getBinary function before your main function, because the compilator cannot recognize your function when it is defined after the call.
int main()
{
unsigned int nr;
unsigned int mask=32;

char *outString;

printf("Enter Nr:\n");
scanf("%u",&nr);

outString = getBinary(nr,mask);
printf("%s",outString);
//getch();
return 0;
}

char * getBinary(int nr,int mask)
{
static char outPut[sizeof(mask)]="";
 while(mask>0)
{
 if((nr&mask)==0)
    {
        strcat(outPut,"0");
    }
    else
    {
        strcat(outPut,"1");
    }
    mask=mask>>1;
  }

//printf("%s",outPut);
return outPut;
}