How can strings be represented in the C programming language using pointers?

In the C language, strings are often represented using character arrays, which are essentially a type of pointer. Therefore, strings can be represented using pointers.

Specifically, one can use a pointer to a character (char) type to represent a string. The pointer points to the first character of the string, and by continuously moving the pointer forward, the entire string can be traversed.

Here is an example demonstrating how to use pointers to represent strings.

#include <stdio.h>

int main() {
    char *str = "Hello, world!";  // 字符串常量赋值给指针变量
    
    // 通过指针遍历字符串,并打印每个字符
    while (*str != '\0') {
        printf("%c", *str);
        str++;  // 指针向后移动
    }
    
    return 0;
}

In the example above, the variable char *str is declared as a pointer to a character and assigned the address of the string constant “Hello, world!”. Then, the characters pointed to by the pointer are iterated through in a loop until the end-of-string character ‘\0’ is encountered.

Please note that string constants are immutable in this case, so operations that modify strings should not be performed on pointers pointing to string constants. If string modifications are needed, character arrays should be used instead.

bannerAds