| New Reply |
Passing Strings as Arguments to Functions in C |
Share Thread | Thread Tools |
| May21-11, 04:24 PM | #1 |
|
Mentor
|
Passing Strings as Arguments to Functions in C
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:
void myfunc(char *message)
{
/* function definition goes in here */
}
/*
.
.
.
and then some time later
*/
myfunc("this is my message");
|
| May21-11, 04:39 PM | #2 |
|
|
[QUOTE=cepheid;3314968]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:
void myfunc(char *message)
{
/* function definition goes in here */
}
/*
.
.
.
and then some time later
*/
myfunc("this is my message");
In reality, the string is probably placed in the data segment of your executable (in a constant section), and the string "this is my message" gets converted into a pointer constant that points into the right location in the data segment. |
| May21-11, 04:57 PM | #3 |
|
Mentor
|
|
| May21-11, 05:54 PM | #4 |
|
|
Passing Strings as Arguments to Functions in CThe 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) |
| May21-11, 08:49 PM | #5 |
|
|
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. |
| May21-11, 09:53 PM | #6 |
|
|
|
| New Reply |
| Thread Tools | |
Similar Threads for: Passing Strings as Arguments to Functions in C
|
||||
| Thread | Forum | Replies | ||
| Converting open strings to closed strings | Beyond the Standard Model | 4 | ||
| Fortran functions as arguments of functions | Programming & Comp Sci | 2 | ||
| Integral Involving Trigonometric Functions with Varying Arguments | Calculus & Beyond Homework | 5 | ||
| Limits of Arguments of Functions | Calculus | 16 | ||
| Fortran 90/95 : passing parameters to functions | Programming & Comp Sci | 4 | ||