Passing Strings To Functions in C
String Function Arguments
In C, you can pass strings to functions in two ways:
- By passing an array of characters (i.e., a string)
- By passing a pointer to the first character in the string.
Passing an array of characters
Here's an example of passing an array of characters (string) to a function:
#include <stdio.h>
void print_string(char str[])
{
printf("%s\n", str);
}
int main()
{
char message[] = "Hello, world!";
print_string(message);
return 0;
}
Output:
Explanation
The
print_stringfunction takes a single argument,str, which is an array of characters (i.e., a string).In the
mainfunction, a string message is defined and initialized with the value "Hello, world!". This string is then passed as an argument to theprint_stringfunction.The
print_stringfunction uses theprintffunction to print the string passed to it, along with a newline character to add a line break after the string.
Passing a pointer to the first character
And here's an example of passing a pointer to a string to a function:
#include <stdio.h>
void print_string(char *str)
{
printf("%s\n", str);
}
int main()
{
char message[] = "Hello, world!";
print_string(message);
return 0;
}
Output:
Explanation
The
mainfunction declares a string message with the value "Hello, world!", and passes it to theprint_stringfunction.The
print_stringfunction takes a pointer to a character as an argument and uses theprintffunction to print the string passed to it, along with a newline character.
- In C, arrays can be automatically converted to pointers, so the two examples are equivalent and produce the same result.
- When passing a string to a function, it's common to pass a pointer to the string, as this allows the function to modify the string if necessary.