函数返回Char数组C.

时间:2016-11-14 10:17:43

标签: c arrays pointers

我尝试从函数返回char数组。我是C的新手,并尝试学习函数返回值。 这是我的代码:

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

我不能让程序工作!函数调用时出现两个错误。

3 个答案:

答案 0 :(得分:2)

主要问题是,sizeof(mask)没有按照您的想法行事。这相当于sizeof(int),这不是你想要的。

为此,你最好坚持使用指针和内存分配器功能。

仅供参考,您目前没有看到

的问题
 static char outPut[sizeof(mask)] "";

因为sizeof是编译时运算符,所以此outPut不是VLA。只要您尝试将其更改为

static char outPut[mask] = "";

你会遇到问题,如

  • VLA是本地范围和不完整类型,不允许static存储。
  • 您无法初始化VLA。

此外,如果您打算在getBinary()之后定义原型(前向声明),则必须将其提供给main()

答案 1 :(得分:0)

您可以更改以下程序:

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

答案 2 :(得分:0)

感谢所有回答,我的问题通过在main之前添加函数原型来解决。关于数组大小[sizeof()]它只是用于测试,对于实时代码我认为更多的alloc()是更多的击球。