![](/img/trans.png)
[英]Is there a function in c that will return the index of a char in a char array?
[英]Function return Char array C
我尝试从函数返回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] = "";
您将面临问题,因为
static
存储。 另外,如果要在main()
之后定义原型,则必须将其原型(转发声明)提供给getBinary()
main()
。
您可以更改程序,如下所示:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.