简体   繁体   English

无法理解如何从C函数返回字符串

[英]cant understand how to return string from function in C

    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. 我从'main'调用'add'来打印这些内容,然后再调用'function'向我返回usern字符串,但是出了点问题。

I get the error when compiling: 编译时出现错误:

[Warning] initialization makes pointer from integer without a cast--> const char *pass1=function(usern); [警告]初始化使指针从整数开始而没有强制转换-> const char * pass1 = function(usern);
[Error] conflicting types for 'function'--> const char *function (char usern[50]) [错误]'功能'的类型冲突-> const char * function(char usern [50])

The error messages you see are due the result of not declaring the function function before using it. 您看到的错误消息是由于使用功能function 之前未声明功能function而导致的。 So the compiler implicitly declares a prototype with int as the default type for function . 因此,编译器隐式声明一个原型,其中原型intfunction的默认类型。 But the actual return type of function conflicts with the implicit int type. 但是function的实际返回类型与隐式int类型冲突。 So you get those errors. 这样您会得到那些错误。

Note that this implicit int rule is no longer valid as it's been removed since C99. 请注意,此隐式int规则不再有效,因为自C99起已将其删除。 This used to be the case in C89/C90. 在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 *);

The lifetime for which the return of function is valid is the same as the lifetime of the parameter usern that's passed to it. function返回有效的生存期与传递给它的参数usern的生存期相同。

This is because no deep copy of the character array is taken. 这是因为未获取字符数组的深层副本

If you attempt to return pass1 from add and use it, then the program behaviour would be undefined since usern would then be out of scope. 如果尝试从add返回pass1并使用它,则程序行为将不确定,因为usern超出范围。

The normal thing to do here in C is to malloc a new string, returning a pointer to it. 正常的事情在这里C是对malloc一个新的字符串,返回一个指针。 Don't forget to call free at some point. 不要忘记在某个时候打free电话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM