0
0
CHow-ToBeginner · 3 min read

How to Pass String to Function Using Pointer in C

In C, you pass a string to a function by passing a pointer to its first character using char * as the function parameter. This pointer points to the string's memory location, allowing the function to access or modify the string. You call the function by passing the string name, which acts as a pointer to its first character.
📐

Syntax

To pass a string to a function, declare the function parameter as char *str. This means the function receives a pointer to a character array (string). When calling the function, pass the string variable name without brackets.

  • void functionName(char *str): Function takes a pointer to a string.
  • functionName(myString): Call function with string variable.
c
void printString(char *str) {
    // str points to the first character of the string
    while (*str != '\0') {
        putchar(*str);
        str++;
    }
    putchar('\n');
}
💻

Example

This example shows how to pass a string to a function using a pointer and print it character by character.

c
#include <stdio.h>

void printString(char *str) {
    while (*str != '\0') {
        putchar(*str);
        str++;
    }
    putchar('\n');
}

int main() {
    char myString[] = "Hello, world!";
    printString(myString);  // Pass string to function
    return 0;
}
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes when passing strings using pointers include:

  • Passing the string with brackets like functionName(myString[]) which is invalid syntax.
  • Modifying string literals through pointers, which causes undefined behavior because string literals are usually stored in read-only memory.
  • Not ensuring the string is null-terminated, causing the function to read beyond the string's end.

Always pass the string variable name without brackets and ensure the string is properly null-terminated.

c
/* Wrong way: passing with brackets */
// printString(myString[]); // Syntax error

/* Right way: pass pointer to first char */
// printString(myString);
📊

Quick Reference

ConceptDescriptionExample
Function parameterPointer to char to receive stringvoid func(char *str)
Passing stringPass string variable name (pointer to first char)func(myString)
String literalUse const char * to avoid modifying literalsvoid func(const char *str)
Null-terminationString must end with '\0' to mark endchar s[] = "text";

Key Takeaways

Pass strings to functions by using a char * parameter pointing to the first character.
Call the function by passing the string variable name without brackets.
Never modify string literals through pointers; use arrays or const pointers instead.
Ensure strings are null-terminated to avoid reading invalid memory.
Use const char * in function parameters if the string should not be changed.