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

问题描述 投票:1回答:2

我想编写一个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;
}

对于输出,第一行打印“是”,这是我期望的。但是,第二行显示“ 44yes”。为什么打印“是”和“ 44”?

c arrays string c11
2个回答
2
投票

这是因为您的字符串未正确以null终止,因此您在sprintf处遇到未定义的行为。这是因为缓冲区太小,无法容纳空终止符。例如这里:

char stroo[3] = "yes";

0
投票
#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]);
}
© www.soinside.com 2019 - 2024. All rights reserved.