how does C language pass strings to functions

There are two ways to pass a string to a function in the C programming language.

  1. Passing a character array (character pointer) as a function parameter:
#include <stdio.h>

// 使用字符数组作为函数参数
void printString(char str[]) {
    printf("%s", str);
}

int main() {
    char str[] = "Hello, World!";
    printString(str);
    return 0;
}
  1. Passing character pointers as function arguments.
#include <stdio.h>

// 使用字符指针作为函数参数
void printString(char *str) {
    printf("%s", str);
}

int main() {
    char str[] = "Hello, World!";
    printString(str);
    return 0;
}

Both character arrays and character pointers can be used to pass strings to functions. It is important to note that when a character array is passed as a parameter to a function, modifications to the string inside the function will affect the original string; however, when a character pointer is passed as a parameter to a function, modifications to the string inside the function will not affect the original string.

bannerAds