关于函数strcpy_s

about the function strcpy_s

本文关键字:strcpy 函数 于函数      更新时间:2023-10-16

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

#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]);中,似乎可以删除。为什么?

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

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