简体   繁体   中英

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.

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 *);

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.

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.

The normal thing to do here in C is to malloc a new string, returning a pointer to it. Don't forget to call free at some point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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