C语言中,字符串是 char 类型的数组(char[] 或 char *),所以字符串数组本质上是字符指针的数组,也就是char *arr[]。 C 没有真正的“字符串对象”,字符串操作全靠数组+指针,注意内存管理和 \0 结尾。

1、静态字符串数组

静态字符串数组通常指在编译时已确定大小和内容的字符串数组,数组中的每个元素是一个指向字符串字面量(字符串常量)的指针。

#include <stdio.h>

int main() {
    const char *colors[] = {"Red", "Green", "Blue", "Yellow"};
    int n = sizeof(colors) / sizeof(colors[0]);

    for (int i = 0; i < n; i++) {
        printf("%s\n", colors[i]);
    }

    return 0;
}

2、 可修改的二维字符数组(固定长度)

如需要修改字符串内容,可以用二维数组。

#include <stdio.h>

int main() {
    char fruits[3][10] = {"Apple", "Banana", "Cherry"};
    
    fruits[1][0] = 'b';  // 修改"Banana"为"banana"

    for (int i = 0; i < 3; i++) {
        printf("%s\n", fruits[i]);
    }

    return 0;
}

3、动态字符串数组(堆分配)

动态字符串数组是字符串数量不固定(动态分配),每个字符串也是动态分配(堆上存储)可读可写,可动态增加或释放。

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

int main() {
    int n = 3;
    char *animals[] = {"Cat", "Dog", "Elephant"};
    char **dynamic_array = malloc(n * sizeof(char *));

    for (int i = 0; i < n; i++) {
        dynamic_array[i] = strdup(animals[i]);  // 复制字符串到堆上
    }

    for (int i = 0; i < n; i++) {
        printf("%s\n", dynamic_array[i]);
        free(dynamic_array[i]);  // 释放每个字符串
    }
    free(dynamic_array);  // 释放指针数组

    return 0;
}

4、字符指针数组(推荐)

适合存储多个字符串,且可以用字符串常量初始化。

#include <stdio.h>

int main() {
    const char *str[] = {
        "Hello",
        "World",
        "C Language"
    };

    for (int i = 0; i < 3; i++) {
        printf("%s\n", str[i]);
    }

    return 0;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表