Passing Strings as Arguments to Functions in C

  1. cepheid

    cepheid 5,190
    Staff Emeritus
    Science Advisor
    Gold Member

    Hey everyone!

    If I have a function that takes a pointer to char (i.e. char array) as an argument, can I pass a "string literal" (I think that is the right term) as an argument to that function, even if that string hasn't previously been declared anywhere? For example:

    Code (Text):


    void myfunc(char *message)
    {

      /* function definition goes in here */

    }

    /*
    .
    .
    .
    and then some time later
    */


    myfunc("this is my message");

     
    Is that allowed? I'm wondering where the memory comes from for the string.
     
  2. jcsd
  3. Hurkyl

    Hurkyl 16,089
    Staff Emeritus
    Science Advisor
    Gold Member

     
  4. cepheid

    cepheid 5,190
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks for the explanation. Just to clarify, what you're saying above is what might happen in the case where I change the data type of the argument to const char*, which I need to do regardless in order to make this work, right?
     
  5. Hurkyl

    Hurkyl 16,089
    Staff Emeritus
    Science Advisor
    Gold Member

    What I said is what (generally) happens to string literals.

    The need to change the argument of your function is because string literals are arrays of const char, not arrays of char.

    (For backwards compatibility, many compilers will let you pass them around as if they weren't const. Maybe the standard does too, I can't remember. But you still better not actually edit them)
     
  6. It is my understanding that the string is allocated in a function 'frame' on the stack whenever you call myfunc("text"). Somebody PM me if I am mistaken.

    Stick with char * str unless you want the string to be unedited. The const (basically) make the compiler alert you when you try to change the string.
     
    Last edited: May 21, 2011
  7. DrGreg

    DrGreg 1,971
    Science Advisor
    Gold Member

    The pointer to the string will be on the stack, but the string itself (array of chars) is likely to be in some other part of memory, as Hurkyl said, and it may well be in memory to be treated as read-only. (It is up to the compiler/linker to decide exactly where.)
     
Know someone interested in this topic? Share a link to this question via email, Google+, Twitter, or Facebook

Have something to add?