我可以在 C 中使用什么而不是"string" C++

What can I use in C instead of "string" from C++

本文关键字:string C++ 什么 我可以      更新时间:2023-10-16

我已经开始在C中进行纸牌游戏,但是我找不到任何东西,而不是string,显然没有在C中使用。这里有一些代码,其中这成为一个障碍:

struct cards {
    string index;
    string colour;
};
void load_cards(cards deck[MAX_C])
{
    int i = 0;
    for (int j = 0; j < 4; j++) {
        deck[i].index = '2';
        deck[i += 1].index = "3";
        deck[i += 1].index = "4";
        deck[i += 1].index = "5";
        deck[i += 1].index = "6";
        deck[i += 1].index = "7";
        deck[i += 1].index = "8";
        deck[i += 1].index = "9";
        deck[i += 1].index = "10";
        deck[i += 1].index = "W";
        deck[i += 1].index = "D";
        deck[i += 1].index = "K";
        deck[i += 1].index = "A";
    }
    for (int j = 0; j < 13; j++) {
        deck[j].colour = "T";
    }
    for (int j = 13; j < 26; j++) {
        deck[j].colour = "k";
    }
    for (int j = 26; j < 39; j++) {
        deck[j].colour = "K";
    }
    for (int j = 39; j < 52; j++) {
        deck[j].colour = "P";
    }
    for (int j = 52; j < 56; j++) {
        deck[j].colour = "JR";
    }
}

string实际上是C 的类,正如其他人指出的那样,它是围绕char数组/指针的包装器(可用于存储chars的序列)。

在C中,您必须手动使用字符数组。您可以通过两种方式(主要是)进行:

  1. 创建一个静态字符数组(大小足够)。
  2. 使用malloc动态创建字符数组。但是,在不再需要数组时,您也必须手动释放它。

当然,由于您使用的是C,您必须明确/手动,照顾好数组溢出条件,重叠,终止等等。