Ali Abdulhussein
Ali Abdulhussein

Reputation: 65

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.

Upvotes: 0

Views: 422

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

The major problem is, sizeof(mask) is not doing what you think it does. This is equivalent to sizeof(int) which is not what you want there.

You should better stick to a pointer and memory allocator function for this purpose.

FYI, you don't see issues currently with

 static char outPut[sizeof(mask)] "";

as sizeof is a compile time operator, so this outPut is not VLA. As soon as you try to change it to

static char outPut[mask] = "";

you'll face problems, as

  • VLAs are local scope and incomplete type, static storage is not allowed.
  • you cannot initialize VLAs.

Also, you must provide the prototype (forward declaration) to getBinary() if you intend to define it after main().

Upvotes: 2

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

Upvotes: 0

Related Questions