Search code examples
c++stringstrcpy

about the function strcpy_s


I want to output the smallest letters of the first letter of three countries, this is the code:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    void smallest_string(char str[][30], int);
    int i;
    char country_name[3][30];
    for (i = 0; i < 3; i++)
        cin >> country_name[i];
    smallest_string(country_name, 3);
    system("pause");
}
void smallest_string(char str[][30], int n)
{
    int i;
    char string[30];
    ***strcpy_s(string, str[0]);***
    for (i = 0; i < n; i++)
        if (strcmp(str[i], string) < 0)
            strcpy_s(string, str[i]);
    cout << endl << "the smallest string is:" << string << endl;
}

In this code strcpy_s(string, str[0]);, it seems can be deleted. Why?


Solution

  • The line strcpy_s(string, str[0]); is essential if you want your loop to start from i = 1.

    However, since you start it from i = 0 it is not strictly required if you also define the following start condition: string[0] == CHAR_MAX and string[1] == 0. But if that is not the case then you will experience undefined behavior.