Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passing-string-to-function #1

Merged
merged 1 commit into from
Oct 31, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions 12-Strings/passing-strings-to-function.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
------------------------------------------------------------------------------------
Strings can be passed to a function in a similar way as arrays.

To pass a one dimensional string to a function as an argument we just write the name of the string array variable.

In the following example we have a string array variable str and it is passed to the function.

Method 1: Pass by value / without using pointers

void function(char str[]);
char str[50];
function(str); // Passing string to a function.

Method 2: Using Pointers

void function(char* str);
char str[50];
function(str); // Passing string to a function.
------------------------------------------------------------------------------------
*/

// Code here explaining concept with comments to guide
#include <stdio.h>
void sayWelcome(char str[]); // Passing string as reference
void sayGoodbye(char* str); // Passing string as a pointer variable

int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
sayWelcome(str); // Passing string to function
sayGoodbye(str);
return 0;
}
void sayWelcome(char str[])
{
printf("Welcome, ");
puts(str);
}
void sayGoodbye(char* str){
printf("Good Bye, ");
puts(str);
}
/*
------------------------------------------------------------------------------------
Challenge: Create a user defined function which accepts string as argument and counts the total number of character in the inputed string.
------------------------------------------------------------------------------------
*/