繁体   English   中英

为什么 strcat_s 导致问题

[英]why strcat_s causing problems

我遇到的问题是我得到随机字符 output 而不是将名字、中间名和姓氏组合起来,这是程序的目的,当我运行调试器时它说问题在 strcat_s 但我不知道是什么问题用它

#include <iostream>
#include <string.h>
class name {
private:
    char first[20], mid[20], last[20];
public:

    name();
    name(const char*, const char*, const char*);
    ~name();
    char* show();
};
name::name()
{
    first[0] = mid[0] = last[0] = '\0';
}
name::name(const char* f, const char* m, const char* l)
{
    size_t lenF = strlen(f), lenM = strlen(m), lenL = strlen(l);
    if (strlen(f) > 20) lenF = 20;
    else if (strlen(m) > 20) lenM = 20;
    else if (strlen(l) > 20) lenL = 20;
    strncpy_s(first, f, lenF);
    strncpy_s(mid, m, lenM);
    strncpy_s(last, l, lenL);
}
name::~name()
{
    std::cout << "distructing..." << std::endl;
}
char* name::show()
{
    char temp[62];
    strcpy_s(temp, first);
    strcat_s(temp, " ");
    strcat_s(temp, mid);
    strcat_s(temp, " ");
    strcat_s(temp, last);
    return temp;
}
int main()
{
    name a("kinan", "fathee", "ayed");
    std::cout << a.show() << std::endl;
}

您返回全名的逻辑不正确。 您有一个局部变量temp并且您正在返回对该变量的引用。 但是,一旦show() function 完成,这个变量就会被销毁。 因此,在您的main function 中,您有一个参考,但它指向已经被破坏的东西。 这就是为什么您在打印时会看到随机字符的原因。 这是您的问题的解决方案。 您需要创建一个动态数组,即一个指针,这样它就不会被破坏。

char *name::show()
{
    int size = strlen(first) + strlen(mid) + strlen(last) + 3;
    char *temp = new char[size];
    strcpy_s(temp, size, first);
    strcat_s(temp, size, " ");
    strcat_s(temp, size, mid);
    strcat_s(temp, size, " ");
    strcat_s(temp, size, last);
    return temp;
}

int main()
{
    name a("kinan", "fathee", "ayed");
    char *temp = a.show();
    std::cout << temp << std::endl;
    delete[] temp;
}

编辑:在您的原始代码中,如果您在返回之前在show function 末尾打印temp ,您将看到temp包含全名。

编辑:Temp 是一个局部变量。 每个局部变量都在函数执行结束时被销毁。 在建议的解决方案中,我在堆上动态创建一个数组。 当我们动态创建一个数组时,它不会自动从堆中移除。 因此,当我返回对该数组的引用并在 main 中使用它时,它仍然有效。

编辑:我在main function 中添加了delete[]来释放 memory。

应该为 '\0' 保留 1 个字符,因此您需要编写strncpy_s(first, f, lenF - 1);

暂无
暂无

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

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