简体   繁体   English

strcpy_s、strcat_s的基本使用

[英]Basic use of strcpy_s , strcat_s

Code代码

char* CreateString(char* string1, char* string2) {
    
    int length = strlen(string1) + strlen(string2);

    // Allocate memory for the resulting string
    char* result = malloc((length) * sizeof(char)); 

    // Concatenate the two strings
    strcpy_s(result, sizeof result, string1);
    strcat_s(result,sizeof result, string2);
    return result;
}

I have this simple code of mine, all i want to do is add them together, but whenever I use strcpy_s or strcat_s it gives this error in the picture But it works if I use the CRT library.我有这个简单的代码,我想做的就是将它们加在一起,但是每当我使用 strcpy_s 或 strcat_s 时,它都会在图片中给出这个错误但是如果我使用 CRT 库,它就可以工作。

Another question is that did I use the Pointers correctly?另一个问题是我是否正确使用了指针? I'm new to this topic and it is confusing so I don't really understand it.我是这个话题的新手,它很混乱,所以我不太明白。

I tried to add Two Sentences together我试着把两个句子加在一起

  1. strings require null terminating character at the end.字符串末尾需要 null 终止字符。 So the buffer is too short.所以缓冲区太短了。

  2. sizeof result gives the size of the pointer not the size of the referenced object. sizeof result给出了指针的大小,而不是引用的 object 的大小。

char* CreateString(char* string1, char* string2) {
    
    size_t length = strlen(string1) + strlen(string2) + 1;
    // or for Windows
    // rsize_t length = strlen(string1) + strlen(string2) + 1;

    // Allocate memory for the resulting string
    char* result = malloc((length) * sizeof(*result)); 

    // Concatenate the two strings
    strcpy_s(result, length, string1);
    strcat_s(result, length, string2);
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM