Important Concept

Passing Strings to Function in C

Let’s see how to pass strings to functions using the C language. A string is a collection of characters enclosed inside double quotes (i.e., “hello everyone”).

Approach

We will create two functions, one is to send a string as a parameter and the other should take the string as input through the parameter.

C Program

#include <stdio.h>
void str (char *str)
{
  printf ("String is: %s", str);
}

int main ()
{
  char string[100];
  printf ("Enter a String:  ");
  scanf ("%s", &string);
  str (string);
  return 0;
}

Input

 Enter a String:  Hello everyone, this is aniket malik.

Output

String is:  Hello everyone, this is aniket malik.

Explanation

void str (char *str)
{
  printf ("String is: %s", str);
}

This is the function that takes the string which we have passed. It has one parameter *str, where * represents a pointer. In the next step, we used a simple print statement to print the string we passed.

int main() {
  char string[100];
  printf("Enter a String:  ");
  scanf("%s",&string);
  str(string);
  return 0;
}

This is the main function where we have declared a variable ‘string’ to store a string obtained from the user; by using a simple scanf statement. In the next step, we called the function str and ‘string’ was given as a parameter to the function str.
Immediately after calling the str() function the control goes to the str function and the code inside it gets executed (i.e., the string is printed).
Since the main method return type is int so we have returned 0.

Conclusion

We have learned about what is a string; how strings are passed into functions, c language code, and an explanation of how to pass strings to functions.

Aniket Malik

Aniket Malik

CERTIFIED TUTOR/TRAINER WITH 300+ REVIEWS

Facing difficulty with

this concept?