#define STDC_WANT_LIB_EXT1 1
#include <stdio.h>
#include <string.h>
int main(void)
{
char preamble[] = "The joke is:\n\n";
char str[][40] = {
"My dog has\'t got any nose.",
"How does your dog smell then?\n",
"My dog smells horrible.\n"
};
unsigned int strCount = sizeof(str) / sizeof(str[0]);
unsigned int length = 0;
for (unsigned int i = 0; i < strCount; ++i)
{
length += strnlen_s(str[i], sizeof(str[i]));
}
**char joke[length + strnlen_s(preamble, sizeof(preamble)) + 1];**
if (strncpy_s(joke, sizeof(joke), preamble, sizeof(preamble)))
{
printf("Error copying preamble to joke.\n");
return 1;
}
for (unsigned int i = 0; i < strCount; ++i)
{
if (strncat_s(joke, sizeof(joke), str[i], sizeof(str[i])))
{
printf("Error copying string str[%u].", i);
return 2;
}
}
printf("%s", joke);
return 0;
}
错误信息:
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(21): error C2057: 应输入常量表达式
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(21): error C2466: 不能分配常量大小为 0 的数组
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(21): error C2133: “joke”: 未知的大小
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(23): warning C4034: sizeof 返回 0
1>f:\code\c语言入门经典\字符串和文本的应用\joining_strings.c(31): warning C4034: sizeof 返回 0