简体   繁体   中英

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.

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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM