Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. How to return a string from a user defined function to main function ?

How to return a string from a user defined function to main function ?

Scheduled Pinned Locked Moved C / C++ / MFC
data-structureshelptutorialquestion
16 Posts 7 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Tarun Jha

    #include
    #include

    int input();

    int main()
    {
    char name[100];

    printf("Enter your name:\\n");
    strcpy(name,input());
    
    printf("\\n%s", name);
    
    return 0;
    

    }

    int input()
    {
    char c[100];
    gets(c);

    return(c);
    

    }

    i am getting this error while running this code. [Warning] passing argument 2 of 'strcpy' makes pointer from integer without a cast. I have tried this code. I know I can do it similarly as that of returning an array from a function to main, but that's too long is there any alternative short method.

    J Offline
    J Offline
    Jochen Arndt
    wrote on last edited by
    #5

    There is no simple method in C to return a string from a function. Possible methods are: 1. Passing a char* pointer to the function and the function fills the passed buffer. In such cases the size of the buffer should be also passed and the return value indicates failure (usually -1) or success (usually length of copied string):

    int input(char *buf, int buf_size)
    {
    char local_buf[100] = "";
    // Use fgets here instead of gets to avoid buffer overruns
    fgets(local_buf, sizeof(local_buf), stdin);
    int len = strlen(local_buf);
    if (buf_size <= len)
    return -1;
    strcpy(buf, local_buf);
    return len;
    }

    2. Letting the function allocate a buffer. The calling function must free the buffer when no longer used:

    char *input()
    {
    char local_buf[100] = "";
    // Use fgets here instead of gets to avoid buffer overruns
    fgets(local_buf, sizeof(local_buf), stdin);
    return strdup(local_buf);
    }

    // Usage
    char *input_str;
    input_str = input();
    // Use string here
    // ...
    // Finally free it
    free(input_str);

    However, in your case there is no need for an own function because it is already provided by the standard C library: fgets - C++ Reference[^].

    1 Reply Last reply
    0
    • T Tarun Jha

      #include
      #include

      int input();

      int main()
      {
      char name[100];

      printf("Enter your name:\\n");
      strcpy(name,input());
      
      printf("\\n%s", name);
      
      return 0;
      

      }

      int input()
      {
      char c[100];
      gets(c);

      return(c);
      

      }

      i am getting this error while running this code. [Warning] passing argument 2 of 'strcpy' makes pointer from integer without a cast. I have tried this code. I know I can do it similarly as that of returning an array from a function to main, but that's too long is there any alternative short method.

      M Offline
      M Offline
      Member 11560490
      wrote on last edited by
      #6

      You can't do this. Because array c is released when input() function execute completed. Maybe you can used "static" key word to prevent array c to released or pass a buffer to input() function as parameter.

      1 Reply Last reply
      0
      • T Tarun Jha

        #include
        #include

        int input();

        int main()
        {
        char name[100];

        printf("Enter your name:\\n");
        strcpy(name,input());
        
        printf("\\n%s", name);
        
        return 0;
        

        }

        int input()
        {
        char c[100];
        gets(c);

        return(c);
        

        }

        i am getting this error while running this code. [Warning] passing argument 2 of 'strcpy' makes pointer from integer without a cast. I have tried this code. I know I can do it similarly as that of returning an array from a function to main, but that's too long is there any alternative short method.

        L Offline
        L Offline
        leon de boer
        wrote on last edited by
        #7

        As per your last post lets fix my code from it into a function .. which is what I assume you are trying to do

        int StringInput (char* name, int namemax)
        {
        int c;
        int namelen = 0; // initialize array position index to zero
        if (name && namemax > 1) { // Lets be safe and check pointer valid and space > 1
        do {
        c = getc(stdin); // fetch the integer keyboard read value .. EOF safe
        name[namelen++] = (char) c; // convert the integer to a char and place in array .. increment position
        } while (c !=EOF && c != '\n' && namelen < namemax-1); // repeat until EOF or new line or hit max length-1 (need space for '\0')
        temp.name[namelen-1] = '\0'; // Make C null terminated string (overwrite last EOF or '\n')
        }
        return(namelen); // return the name length
        }

        /** HOW to USE *//
        int main(void)
        {
        char name[100];
        int len = StringInput(&name[0], sizeof(name));
        // OR if you don't need length just
        StringInput(&name[0], sizeof(name));
        }

        Now if this is for uni or commercial then you probably want this form ... An excercise for you is to understand why and how to do it

        int StringInput (const char* name, const int namemax, const FILE* source)

        In vino veritas

        T 1 Reply Last reply
        0
        • L leon de boer

          As per your last post lets fix my code from it into a function .. which is what I assume you are trying to do

          int StringInput (char* name, int namemax)
          {
          int c;
          int namelen = 0; // initialize array position index to zero
          if (name && namemax > 1) { // Lets be safe and check pointer valid and space > 1
          do {
          c = getc(stdin); // fetch the integer keyboard read value .. EOF safe
          name[namelen++] = (char) c; // convert the integer to a char and place in array .. increment position
          } while (c !=EOF && c != '\n' && namelen < namemax-1); // repeat until EOF or new line or hit max length-1 (need space for '\0')
          temp.name[namelen-1] = '\0'; // Make C null terminated string (overwrite last EOF or '\n')
          }
          return(namelen); // return the name length
          }

          /** HOW to USE *//
          int main(void)
          {
          char name[100];
          int len = StringInput(&name[0], sizeof(name));
          // OR if you don't need length just
          StringInput(&name[0], sizeof(name));
          }

          Now if this is for uni or commercial then you probably want this form ... An excercise for you is to understand why and how to do it

          int StringInput (const char* name, const int namemax, const FILE* source)

          In vino veritas

          T Offline
          T Offline
          Tarun Jha
          wrote on last edited by
          #8

          Quote:

          if (name && namemax > 1)

          . why name is there when it is a char, and how can it be > 1?? And it works fine if i remove it.

          V L L 3 Replies Last reply
          0
          • T Tarun Jha

            Quote:

            if (name && namemax > 1)

            . why name is there when it is a char, and how can it be > 1?? And it works fine if i remove it.

            V Offline
            V Offline
            Victor Nijegorodov
            wrote on last edited by
            #9

            Tarun Jha wrote:

            Quote:

            if (name && namemax > 1)

            . why name is there when it is a char, and how can it be > 1?? And it works fine if i remove it.

            You could rewrite it to be:

            if (name != NULL && namemax > 1))

            that means that name points to some space in memory and the length of this "space" (character array) is > 1. And "it works fine if i remove it" only means that name != NULL and namemax > 1

            T 1 Reply Last reply
            0
            • T Tarun Jha

              Quote:

              if (name && namemax > 1)

              . why name is there when it is a char, and how can it be > 1?? And it works fine if i remove it.

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #10

              Tarun Jha wrote:

              And it works fine if i remove it.

              It does not work fine if you remove it because you now have a rather hidden bug in your code. Get hold of a good book on C (as I have repeatedly suggested) and issues like this will become clear.

              T 1 Reply Last reply
              0
              • V Victor Nijegorodov

                Tarun Jha wrote:

                Quote:

                if (name && namemax > 1)

                . why name is there when it is a char, and how can it be > 1?? And it works fine if i remove it.

                You could rewrite it to be:

                if (name != NULL && namemax > 1))

                that means that name points to some space in memory and the length of this "space" (character array) is > 1. And "it works fine if i remove it" only means that name != NULL and namemax > 1

                T Offline
                T Offline
                Tarun Jha
                wrote on last edited by
                #11

                Thank you

                1 Reply Last reply
                0
                • L Lost User

                  Tarun Jha wrote:

                  And it works fine if i remove it.

                  It does not work fine if you remove it because you now have a rather hidden bug in your code. Get hold of a good book on C (as I have repeatedly suggested) and issues like this will become clear.

                  T Offline
                  T Offline
                  Tarun Jha
                  wrote on last edited by
                  #12

                  i bought k&r but it's a bit difficult for me to understand.

                  L 1 Reply Last reply
                  0
                  • T Tarun Jha

                    i bought k&r but it's a bit difficult for me to understand.

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #13

                    K&R is probably the easiest introduction to C. If you find it hard then you need to read it through quite a few times.

                    T 1 Reply Last reply
                    0
                    • T Tarun Jha

                      Quote:

                      if (name && namemax > 1)

                      . why name is there when it is a char, and how can it be > 1?? And it works fine if i remove it.

                      L Offline
                      L Offline
                      leon de boer
                      wrote on last edited by
                      #14

                      Again Richard MacCutchan is correct so let me explain my code name is a "pointer to a char" NOT a char So this line

                      if (name && namemax > 1)

                      Is a shortcut of writing

                      if ( (name != 0) && (namemax > 1) )

                      writing

                      if (anything)

                      Basically checks if the thing called "anything" is not zero its a shortcut So what the line it is checking is the pointer called name is not 0 (or null which is an invalid pointer) the space for the buffer name is greater than 1 .. why well the code specifically makes an '\0' terminated C string so it needs a minimum buffer size of 1 to hold the '\0' So name == 0 or namemax == 0 would bug the code so they are specifically handled. So the line is a specific safety to make sure you could NEVER bug the routine doing either the function will simply return 0 which is correct it read no character data. There are a couple of other possible background bugs and program hints which was in my hint to change the interface. 1.) The use of "stdin" could be possibly problematic in some esoteric systems .. you don't know it's actually a device there might be no keyboard etc on the system. As such bringing it in thru the interface pass that responsibility out to the caller code. 2.) We don't ever change name or namemax internally so placing a const in front of them makes it clear that is the case and also allows the optimizer to really go to work. So it's not a bug fix but a help to the compiler and anyone using the code. So that is as robust to function input error as I can make your function. You are left with two possible errors outside my control passing in a pointer to some wrong place and passing in a wrong maximum buffer size. I would have to be a mind reader to be able to deal with those but I have dealt with all the obvious possible errors.

                      In vino veritas

                      T 1 Reply Last reply
                      0
                      • L leon de boer

                        Again Richard MacCutchan is correct so let me explain my code name is a "pointer to a char" NOT a char So this line

                        if (name && namemax > 1)

                        Is a shortcut of writing

                        if ( (name != 0) && (namemax > 1) )

                        writing

                        if (anything)

                        Basically checks if the thing called "anything" is not zero its a shortcut So what the line it is checking is the pointer called name is not 0 (or null which is an invalid pointer) the space for the buffer name is greater than 1 .. why well the code specifically makes an '\0' terminated C string so it needs a minimum buffer size of 1 to hold the '\0' So name == 0 or namemax == 0 would bug the code so they are specifically handled. So the line is a specific safety to make sure you could NEVER bug the routine doing either the function will simply return 0 which is correct it read no character data. There are a couple of other possible background bugs and program hints which was in my hint to change the interface. 1.) The use of "stdin" could be possibly problematic in some esoteric systems .. you don't know it's actually a device there might be no keyboard etc on the system. As such bringing it in thru the interface pass that responsibility out to the caller code. 2.) We don't ever change name or namemax internally so placing a const in front of them makes it clear that is the case and also allows the optimizer to really go to work. So it's not a bug fix but a help to the compiler and anyone using the code. So that is as robust to function input error as I can make your function. You are left with two possible errors outside my control passing in a pointer to some wrong place and passing in a wrong maximum buffer size. I would have to be a mind reader to be able to deal with those but I have dealt with all the obvious possible errors.

                        In vino veritas

                        T Offline
                        T Offline
                        Tarun Jha
                        wrote on last edited by
                        #15

                        Thank you for your elaborated explanation i was able to understand and learn many new things.

                        1 Reply Last reply
                        0
                        • L Lost User

                          K&R is probably the easiest introduction to C. If you find it hard then you need to read it through quite a few times.

                          T Offline
                          T Offline
                          Tarun Jha
                          wrote on last edited by
                          #16

                          i will do it as many times as needed until i get the concepts.

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups