Passing Strings to Functions

In C, strings are represented as arrays of characters, typically terminated by a null character '\0'. You can pass strings to functions in several ways. Here's an example of how to pass strings to functions in C:

Example:


#include <stdio.h>
#include <string.h>

// Function to print a string passed as an array of characters
void printString(char str[]) {
    printf("String: %s\n", str);
}

// Function to calculate and return the length of a string
int stringLength(char str[]) {
    int length = 0;
    while (str[length] != '\0') {
        length++;
    }
    return length;
}

int main() {
    char myString[] = "Hello, World!";

    // Passing a string to the printString function
    printf("Original String: %s\n", myString);
    printString(myString);

    // Passing a string to the stringLength function to calculate its length
    int length = stringLength(myString);
    printf("Length of the string: %d\n", length);

    return 0;
}
    

In this example:

  • The printString function takes a character array str as a parameter and prints it using the %s format specifier.
  • The stringLength function calculates and returns the length of a string by counting characters until it encounters the null character '\0'.
  • Inside the main function, a character array myString is defined, initialized with a string, and passed to both functions.

Output:


Original String: Hello, World!
String: Hello, World!
Length of the string: 13
    

When passing strings to functions, you are essentially passing a pointer to the first character of the string. The functions can then access and manipulate the characters in the string as needed.

It's important to note that C strings are mutable, so functions can modify the contents of the string if necessary. However, when modifying strings in functions, be cautious about buffer overflows to prevent memory corruption.

Additionally, you can pass strings as pointers to characters (char*) to achieve the same result, and this is a common practice in C.


void printString(char* str);
int stringLength(char* str);
    

Both char str[] and char* str are commonly used to represent strings in C, and they are interchangeable when passing strings to functions.