2016-11-14 161 views
-1

我尝试从函数返回字符数组。我是C新手,并尝试学习函数返回值。 这是我的代码:函数返回字符数组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; 
} 

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

+1

你得到什么错误? –

+0

函数的隐式声明。并赋值使指针ROM整数与一个铸造。 –

+3

试着把一个'char * getBinary(int nr,int mask)'原型放在'''' – artm

回答

0

感谢所有的答案,我的问题,通过前主加入函数原型解决。关于数组大小[sizeof()]它只是为了测试,对于实时代码,我认为更多的alloc()会更加糊口。

2

主要问题是,sizeof(mask)没有做你认为它的事情。这相当于sizeof(int),这不是你想要的。

为了达到这个目的,你最好坚持一个指针和内存分配器的功能。

仅供参考,看不到问题目前与

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

sizeof是一个编译时操作,因此这outPut不是VLA。只要你尝试改变它

static char outPut[mask] = ""; 

你要面对的问题,因为

  • VLAS是局部范围不完整的类型,static存储是不允许的。
  • 您无法初始化VLA。

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

+0

返回一个局部变量(数组)'outPut'导致UB,即使它是静态的? – Gopi

+1

他的问题是他没有函数原型'getBinary()' – Gopi

+0

@Gopi还有一个更大的,隐藏的, –

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