Changing the size of an array passed to a function problem!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • srbakshi
    New Member
    • Aug 2008
    • 18

    Changing the size of an array passed to a function problem!

    Hi all,

    I have the following scenario:

    Code:
    int main()
    {
       char a[] = "Hello";
       printf("Modified string: %s\n", modify_str(a));
    }
    
    char *modify_str(char *b)
    {
       /* Insert a  '+'  after every letter in the string */
       /* "Hello" becomes "H+e+l+l+o+" */
       return b;
    }
    Now my problem is that the length of the string doubles after the operation is over. So how do I re-size the memory pointed to by 'b' to accommodate the change in size of the string?

    I cannot have a local array of twice the size of 'b' and return that because that would be returning a local pointer.

    Will this be correct and work fine? -->
    Code:
    char *modify_str(char *b)
    {
       char *local;
       local = (char *)malloc(strlen(b)*2 + 1);
       /* 'local' gets filled up with the modified 'b' */
       b = local;    /* Is this wrong? Why is this wrong?? */
       return b;
    }
    Please if somebody could help :((
    -
    -Sid
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Yes you could that and it'll work fine (don't forget to free that chunk of memory when you don't need it anymore) but if we're talking C++ there's the string class which does it all for you.

    kind regards,

    Jos

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      A few points, to start with this

      Code:
          b = local;    /* Is this wrong? Why is this wrong?? */
          return b;
      pointlessly modifies b and can be written as

      Code:
          return local;
      Modifying b does nothing for you and is an operation that has no effect on the operation of main.

      You have malloc'd the data for use in the return pointer, that means at some point you will need to free it otherwise you will have a memory leak. That means that the calling code can not just use the return pointer (pass it straight to printf) but has to store it in another variable so that it can free the data pointed to after calling printf.

      And finally some people would consider it bad form to write code such that the calling function has to have knowledge of how the called function operates internally in order to correctly use it. A better method to write this function might be for it to have 2 parameters, 1 pointer to the source string and 1 pointer to the place to store the result string. The calling function would have to make sure the result string had enough characters to store the result. Or better yet add a third parameter, the size of the result string and the function caninsure that it does not overwrite the end of it.

      Comment

      • srbakshi
        New Member
        • Aug 2008
        • 18

        #4
        Originally posted by Banfa
        And finally some people would consider it bad form to write code such that the calling function has to have knowledge of how the called function operates internally in order to correctly use it. A better method to write this function might be for it to have 2 parameters, 1 pointer to the source string and 1 pointer to the place to store the result string. The calling function would have to make sure the result string had enough characters to store the result. Or better yet add a third parameter, the size of the result string and the function caninsure that it does not overwrite the end of it.
        Thanks to you Mr.Banfa I got my code working after incorporating the above suggestions. I'm thankful to you for telling me a more efficient way of doing this.
        Thanks to Mr.JoshAH as well.

        I guess this question really boils down to the solution for returning a char array from a function. :p
        Be back with more queries as I learn.
        -Sid

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Originally posted by srbakshi
          I guess this question really boils down to the solution for returning a char array from a function. :p
          You cannot return arrays from a function. You can only return a type or a pointer to a type.

          First, read this article: http://bytes.com/topic/c/insights/77...rrays-revealed.

          Assuming you have read the article at this point, you can see that you pass the address of element 0 of the array to the function as an argument and the function can then access the array through the pointer.

          Comment

          • unauthorized
            New Member
            • May 2009
            • 81

            #6
            There is another method to achieve what you want: pass a char** pointer.
            You can do the following:

            Code:
            void MyFunc(char** ppString)
            {
                 // notice how we dereference ppString to get the initial pointer
                 ralloc( *ppString, strlen(ppString) * 2 + 1);
                 *ppString[ strlen(ppString) * 2 ] = 0; // ensure that the string is terminated
            
                 // TODO: modify the contents of ppString any way you want
                 // you can use *ppString[i] to access individual characters
            }
            
            char* pStr;
            // TODO: init pStr
            MyFunc(&pStr);
            The above code will resize pStr and change it's contents in any way you want it. For safety reasons, you should add another integer that will contain the string size. You could also optimize the function further by using fastcall calling conversion, but this is compiler specific.

            This is generally, the fastest way to do it and has virtually no memory overhead. On the other hand if performance isn't an issue and can you use a C++ compiler, std::string will make your life much easier.

            Comment

            • srbakshi
              New Member
              • Aug 2008
              • 18

              #7
              Originally posted by weaknessforcats
              You cannot return arrays from a function. You can only return a type or a pointer to a type.

              First, read this article: http://bytes.com/topic/c/insights/77...rrays-revealed.

              Assuming you have read the article at this point, you can see that you pass the address of element 0 of the array to the function as an argument and the function can then access the array through the pointer.
              weaknessforcats that was a wonderful tut. I was actually referring to the solution given by Banfa, which is nothing but a solution to the problem of not being able to "return" string.
              A better method to write this function might be for it to have 2 parameters, 1 pointer to the source string and 1 pointer to the place to store the result string. The calling function would have to make sure the result string had enough characters to store the result. Or better yet add a third parameter, the size of the result string and the function caninsure that it does not overwrite the end of it.
              :O)

              @unauthorized
              Thanks a lot for telling about the alternate way of doing this although I gotta admit double pointers make me a little woozy! :p Deferring implementation until coding God-mode is acquired. :O)

              Thanks again,
              Sid.

              Comment

              Working...