Like Tree1Likes

A function that returns char*

This is a discussion on A function that returns char* within the C Programming forums, part of the General Programming Boards category; Hey guys! I was wondering, if I have a function like so: char* function() Code: { char *x; ...... ...... ...

  1. #1
    Registered User
    Join Date
    Jul 2011
    Posts
    13

    A function that returns char*

    Hey guys!
    I was wondering, if I have a function like so:
    char* function()
    Code:
    {
      char *x;
      ......
      ......
      ......
      return X
    }
    Than how do I get the return value into another variable?
    can I just do:

    Code:
    struct->string = function();
    or do I have to do:

    Code:
    strcpy(struct->string,function());

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    That depends on how the function works. If you have the kind of function that malloc's memory every time it is called, then the first is fine, although the second one will then cause a leak since you have no way to free the memory created by function().

    If you have the kind of function that keeps a static buffer, then the first might work if you know you will either (a) never calll the function again or (b) if you do, you don't care about the old value any more. The second will work much better (giving you your own copy that will stay put if you call function() again), although struct->string needs to point somewhere first.

    If you have the kind of function that does neither of these, then it is broken so it doesn't matter what you do.

  3. #3
    Registered User
    Join Date
    Jul 2011
    Posts
    13
    I do have the first function you've mentioned it just mallocs a char pointer, so your'e saying I should get rid of it?

  4. #4
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Well, when in doubt just try it out:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char* myFunction(char*);
    
    int main(void){
    
    	struct myStruct{
    		char *myPointer;
    	}myExample;
    
    	char myLine[10];
    
    	myExample.myPointer=myFunction(myLine);
    
    	printf("%s", myExample.myPointer);
    
    	getchar();
    	return (0);
    }
    char* myFunction(char* myAnswer){
    	printf("Enter a line:");
    	fgets(myAnswer, 9, stdin);
    	return myAnswer;
    }
    Note that you cannot create the variable locally and then return a pointer to it outside of a function as this is undefined behavior.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by Aviel Krantz View Post
    I do have the first function you've mentioned it just mallocs a char pointer, so your'e saying I should get rid of it?
    I meant (but got perhaps over optimistic with my pronouns) that if you've got a function that mallocs its own memory, then the first [form of what you had typed] is fine, but the second one is not. So use the first form.

  6. #6
    Registered User
    Join Date
    Jul 2011
    Posts
    13
    Ok I got you both, but for example can I do this?:

    Code:
    char* emailGet(char *temp)//getting the email
    {
         printf("Enter email: ");
         scanf("%s",temp);
         while(emailCheck(temp) == 1)//if the email is invalid it will return 1
         {
              temp = realloc(sizeof(char),20);
              if(temp == NULL)
                fail();
              myCls();
              printf("Invalid email re-enter email: ");
              scanf("%s",temp);
         }
         return temp;
    }
    Or because temp is a parameter I don't even need to return him?
    sorry for dumb question I'm having some troubles with pointers..

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Remember: any changes you make to a parameter disappear when the function ends. In this case, any changes you make to the value of temp (as opposed to where temp points; the value itself) will vanish. Changes like:
    Code:
    temp = realloc(sizeof(char), 20);
    Now this realloc call will fail miserably, because those aren't the arguments to realloc -- you should read the manual. But once you get the realloc call fixed, if you want to see those changes, you must return those changes, and that's what your return statement does.

  8. #8
    Registered User
    Join Date
    Jul 2011
    Posts
    13
    Ohh I just watched this realloc my bad it used to be a malloc..
    Ok, I understand you!

    now one more thing, what am I supposed to understand from this error?
    parameter "pass" has just a forward declaration

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    That means you're trying to pass something fancy into a function, but you've never told the compiler what that kind of fancy object is. If you declare a new type, then all functions that use objects of that type must be able to see the declaration of the type (typical method is to put it in a header and #include that header).

  10. #10
    Registered User
    Join Date
    Jul 2011
    Posts
    13
    Ok all of the errors are fixed, now time for some bugs...

    So I have this function:

    Code:
    char* emailGet(char *email)//getting the email
    {
         users *current;
         point:
         current = Users
         printf("Enter email: ");
         scanf("%s",email);
         if(strstr(email,"@gmail.com") != NULL && strstr(email,".com") == email+strlen(email)-4 && strstr(email,"@gmail.com") > email)
         {
            for( ; current->n_user != NULL ; current = current->n_user)
            {
                 if(strcmp(current->email,email) == 0)
                 {
                   email = realloc(email,15);
                   printf("Email already exists, re-enter the email");
                   goto point;
                 }
            }
            return email;
         }
         else 
         {
             email = realloc(email,15);
             printf("Email already exits, re-enter email\n");
             goto point;
         }
    }
    For some reason the loop crashes it..

  11. #11
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    You should pick an indentation style and run with it -- it will help you see what's in your loop and what isn't. Also, goto == Very Bad. Why not just be a normal person and use a while or a do-while loop? Also your for loop doesn't do what you think it does. (ETA: Also how you got the else to still attach to the if from two blocks away indicates something untoward happening here, like you pasting half your code, incorrectly, in the hopes that we will magically guess what your code actually looks like.)

    Also, if email did not originally come from malloc, then attempting to realloc it will fail horribly.

  12. #12
    Registered User
    Join Date
    Jul 2011
    Posts
    13
    "email" has been "malloced" outside the function before the function was called,
    I changed the goto, I used it just because it makes it look less messy.
    and I don't see any other way of the loop to work (the for one), it's pretty much straight forward..

    this is the code after the changes:

    Code:
    char* emailGet(char *email)//getting the email
    {
         users *current = Users;
         printf("Enter email: ");
         scanf("%s",email);
         if(strstr(email,"@gmail.com") != NULL && strstr(email,".com") == email+strlen(email)-4 && strstr(email,"@gmail.com") > email)
         {
            for( ; current->n_user != NULL ; current = current->n_user)
            {
                 while(strcmp(current->email,email) == 0)
                 {
                   printf("Email already exists, re-enter the email");
                   email = realloc(email,15);
                   scanf("%s",email);
                   current = Users;
                 }
            }
            return email;
         }
         
         return INVALID;
    }
    invalid = 1

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Hang on just one moment. You are returning 1 as a char*? That seems ... ill-advised, as someone is probably going to try to use that as a real pointer later, and that would be Unfortunate. If you are getting a crash in the function itself, then that means that your list is not actually put together properly (current or current->n_user pointing off into the weeds). I also think you think your realloc function is doing something, which is ludicrous.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,720
    Returning a null pointer to denote INVALID may be better.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Jul 2011
    Posts
    13
    The thing is, as I understand it, if I allocate 20 chars and only use 10, than the other 10 are gone, and that means if someone will later edit the email and will enter a 20 chars email it will leak.

    about the loop, I believe that I've spotted the problem, when this function is called there are no other NODEs in the list, that means that it wont even enter the for loop. so the good option to solve this is to make an if, but what condition will it hold?

    and if I wont return something (in case the email is not gmail) than it means it will send a NULL?

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A function returns a structure
    By xinwu in forum C Programming
    Replies: 3
    Last Post: 01-19-2011, 12:37 AM
  2. function that returns string
    By nik2 in forum C Programming
    Replies: 3
    Last Post: 02-08-2010, 10:24 AM
  3. function returns 0
    By alyeska in forum C++ Programming
    Replies: 11
    Last Post: 11-04-2008, 02:15 AM
  4. how do I declare a function that returns a char array
    By cxs00u in forum C++ Programming
    Replies: 1
    Last Post: 03-21-2002, 10:38 AM
  5. function returns int *
    By aripata in forum C Programming
    Replies: 1
    Last Post: 09-06-2001, 07:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21