如何在二维数组中存储多个字符串?

How to store multiple strings in a 2-D array?

我想编写一个 C 程序,在 运行 时存储一堆句子,并在程序结束时打印出来。 这是我写的:

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

int main(){
    int counter = 0;
    char state[100][200];
    char stroo[3] = "yes";
    sprintf(state[counter], "%s", stroo);
    counter++;
    char poo[2] = "44";
    sprintf(state[counter], "%s", poo);
    counter++;
    for (int i=0; i<counter; i++) {
        printf("%s\n", state[i]);
    }
    return 0;
}

对于输出,第一行打印出 "yes",这正是我所期望的。然而,第二行打印“44yes”。为什么打印 "yes" 以及“44”?

那是因为你的字符串没有正确地以 null 结尾,所以你 运行 在 sprintf 处进入了未定义的行为。这是因为缓冲区太小,无法容纳空终止符。例如这里:

char stroo[3] = "yes";

您需要存储四个字符,'y''e''s' 和空终止符。改成

char stroo[4] = "yes";

同样 char poo[2] 需要 char poo[3]

参见 here(强调我的):

Successive bytes of the string literal or wide characters of the wide string literal, including the terminating null byte/character, initialize the elements of the array [...] If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored:

如果您希望尺寸自动足够大以完全适合字符串,您可以省略尺寸说明:

char stroo[] = "yes";

当然,对于这个例子,您甚至不需要将字符串复制到堆栈中:

char *stroo = "yes";
#define STRINGS 5
#define STRING_SIZE 50

char arr[STRINGS][STRING_SIZE] =
{ "Hi",
  "Hello world",
  "Good morning",
  "ASDF",
  "QWERTY"
};

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