//program 6.4 joining strings
#define STDC_WANT_LIB_EXT1 1
#include
#include
int main(void)
{
char preamble[] = "the joke is:\n\n";
char str[][40] = {
"My dog hasn\'t got any nose.\n",
"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;
}
這段代碼到底是怎麼組合字符的,搞了半天只看懂一點!
希望大神能給詳細解釋解釋 (快到指針了,好激動)
#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 hasn\'t got any nose.\n",
"How does your dog smell then?\n",
"My dog smells horrible.\n"
};
// 計算出str數組中的str個數,本程序中str值為3
unsigned int strCount = sizeof(str)/sizeof(str[0]);
unsigned int length = 0;
// strnlen_s函數返回字串的長度
for (unsigned int i = 0; i < strCount ; ++i)
length += strnlen_s(str[i], sizeof(str[i]));
// length為str數組中的字符串拼接後總長度
char joke[length + strnlen_s(preamble, sizeof(preamble)) + 1];
// 先strncpy_s函數拷貝,再strncat_s函數連接,作用區域都是joke
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;
}