关于函数strcpy_s

时间:2017-03-22 09:24:28

标签: c++ string strcpy

我想输出三个国家的第一个字母的最小字母,这是代码:

#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;
}

在此代码strcpy_s(string, str[0]);中,似乎可以删除。为什么呢?

1 个答案:

答案 0 :(得分:1)

如果您希望循环从strcpy_s(string, str[0]);开始,则行i = 1是必不可少的。

但是,由于您是从i = 0启动的,因此如果您还定义了以下开始条件,则不是严格要求的:string[0] == CHAR_MAXstring[1] == 0。但如果情况并非如此,那么您将遇到未定义的行为。