我想编写一个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”?
这是因为您的字符串未正确以null终止,因此您在sprintf
处遇到未定义的行为。这是因为缓冲区太小,无法容纳空终止符。例如这里:
char stroo[3] = "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]);
}