简体   繁体   中英

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.

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. So the buffer is too short.

  2. sizeof result gives the size of the pointer not the size of the referenced 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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