Strings passing is functions

Home / C Programming / Strings passing is functions

Strings passing is functions


In C programming, strings are represented as arrays of characters, and when you pass a string to a function, you typically pass it as a pointer to the first character of the array. This way, the function can access the characters of the string and manipulate it directly. C does not have a built-in string data type like some other programming languages, so strings are essentially treated as character arrays.

Here's an example to demonstrate passing a string to a function:


Output:

Before function call: Hello, world!

Inside the function: Hello, world!

After function call: Hello, world!

In this example, the `printString` function takes a string (character array) as an argument. The function then prints the string without making any changes to it. When you call `printString(myString)` from the `main` function, you pass the address of the first character of the `myString` array to the function, and it can access and print the characters of the string directly.

If you want to modify the string inside the function, you can pass it as a pointer to a character. This way, the function can access the characters of the string and update them directly.

Here's an example of how to modify a string inside a function using a pointer:


Output:

Before function call: Hello, world!

After function call: Hello, world! (Modified)

In this example, the `modifyString` function takes a pointer to a character (`char *`) as an argument. It uses the `strcat` function from the `<string.h>` library to concatenate the string " (Modified)" to the original string, effectively modifying it.