c - 函数返回字符数组 C

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

我无法让程序运行!函数调用有两个错误。

最佳答案

主要问题是,sizeof(mask) 没有按照您的想法进行。这等同于 sizeof(int),这不是您想要的。

为此,您最好坚持使用指针和内存分配器函数。

仅供引用,您目前没有发现问题

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

因为 sizeof 是一个编译时运算符,所以这个 outPut 不是 VLA。一旦您尝试将其更改为

static char outPut[mask] = "";

你会遇到问题,因为

  • VLA 是本地范围和不完整类型,不允许静态 存储。
  • 您不能初始化 VLA。

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

关于c - 函数返回字符数组 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40586337/

相关文章:

c - 如何警告指向超出范围的局部变量的指针

c - 获取条件表达式的地址

c++ - 如何添加自定义关键字以 clang 格式处理为 "class"?

c - 这个程序如何创建僵尸进程?

ruby - 在 Ruby 中获取 block 返回 true 的第一个可枚举元素的最快方法是什么?

c - 将 argv 存储到 int 数组

Windows 上的 Python C 扩展。错误 : not found vcvarsall. bat

c - atof() 的错误行为

javascript - 将第一个元素移动到数组末尾的最快方法

C++ - 重新解释此数据的最快方法