Skip to main content

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_string function takes a single argument, str, which is an array of characters (i.e., a string).

  • In the main function, a string message is defined and initialized with the value "Hello, world!". This string is then passed as an argument to the print_string function.

  • The print_string function uses the printf function 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 main function declares a string message with the value "Hello, world!", and passes it to the print_string function.

  • The print_string function takes a pointer to a character as an argument and uses the printf function to print the string passed to it, along with a newline character.

note
  • 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.