Passing strings to functions in C

In this article, we will create a program for passing strings to functions.

Program

#include<stdio.h>
int show(char str[])
{
            printf("String:");
            puts(str);
}
int main()
{
            char S[30];
            printf("Enter a string\n");
            gets(S);
            show(S);
            return 0;
}

 

Output

Passing strings to functions in C

Explanation

The string is nothing else but an array of characters. Passing of string in the function is done in the same way as we had passed array in functions as arguments.

In the ‘show’ function declaration int show(char str[]) we pass a ‘char’ type string variable ‘str’.

char S[30]; a string variable ‘S’ is declared in the ‘main’ function with size 30. Using the gets function we will store a string in it.

show(S); ‘S’ is passed in the ‘show’ function which will thus display the string entered by the user.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.