不能理解如何从C中的函数返回字符串 [英] cant understand how to return string from function in C

查看:117
本文介绍了不能理解如何从C中的函数返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  void add()
{
char name [50],surname [50],usern [50];

int id,birth,amount;
printf(输入你的名字,姓氏和出生年份:\\\
);
scanf(%s%s%d,& name,& surname,& birth);
printf(输入您的ID,用户名和您的总金额:\\\
);
scanf(%d%s%d,& id,& usern,& amount);
const char * pass1 = function(usern);

$ b $ const char *函数(char usern [50])
{
char temp;
int i = 0;
int j;
j = strlen(usern) - 1;
while(i {
temp = usern [i];
usern [i] = usern [j];
usern [j] = temp;
i ++;
j--;
}
返回usern;
}

我从'main'调用'add'打印这些东西,然后I调用'函数'返回给我的 usern 字符串,但出错了。



编译时出现错误:
$ b


警告初始化使得整型指针没有转换 - > const char * pass1 = function(usern);
$
'function' - > const char *函数(char usern [50])
[错误]冲突类型


解决方案

您看到的错误消息是由于在使用之前未使用函数 声明的结果它。因此,编译器隐式声明了一个原型,其中 int 作为函数的默认类型。但是函数的实际返回类型与隐式 int 类型冲突。所以你会得到这些错误。

请注意,这个隐式的int规则不再有效,因为它自C99以后就被删除了。 C89 / C90就是这种情况。



解决方案是为它提供一个原型。在源文件的顶部添加它(或者将它包含在头文件中,如果有的话):

  const char *函数(char *); 


    void add()
    {    
    char name[50], surname[50], usern[50];

    int id, birth, amount;
    printf("Enter your name, surname and your year of birth:\n");
    scanf("%s %s %d", &name, &surname, &birth);
    printf("Enter your ID, username and your total amount:\n");
    scanf("%d %s %d", &id, &usern, &amount);
    const char *pass1=function(usern);  
    }

  const char *function (char usern[50])
  {
    char temp;
    int i=0;
    int j;
    j = strlen(usern) - 1;
    while (i < j) 
    {
      temp = usern[i];
      usern[i] = usern[j];
      usern[j] = temp;
      i++;
      j--;
    }
    return usern;   
  }

I call 'add' from 'main' to print those things and then I call 'function' to return me the usern string but something goes wrong.

I get the error when compiling:

[Warning] initialization makes pointer from integer without a cast--> const char *pass1=function(usern);
[Error] conflicting types for 'function'--> const char *function (char usern[50])

解决方案

The error messages you see are due the result of not declaring the function function before using it. So the compiler implicitly declares a prototype with int as the default type for function. But the actual return type of function conflicts with the implicit int type. So you get those errors.

Note that this implicit int rule is no longer valid as it's been removed since C99. This used to be the case in C89/C90.

The solution is to provide a prototype for it. Add this at the top of your source file (or include it in a header file if you have one).:

const char *function (char *);

这篇关于不能理解如何从C中的函数返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆