qq_24432057 2015-11-10 12:42 采纳率: 42.9%
浏览 1580
已采纳

以下字符串是怎么连接的,求解释

//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;

}
这段代码到底是怎么组合字符的,搞了半天只看懂一点!
希望大神能给详细解释解释 (快到指针了,好激动)

  • 写回答

1条回答 默认 最新

  • cxlovu 2015-11-10 15:01
    关注
    #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;
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?