我的strcpy_s无法使用我的字符*指针,为什么?

My strcpy_s won't work with my char *pointer, why?

本文关键字:我的 指针 为什么 字符 strcpy      更新时间:2023-10-16

好的,所以我正在尝试修复C++赋值,但当我使用strcpy_s时,它只适用于我的数组,而不适用于*指针。。这是我正在使用的:

HotelRoom::HotelRoom(char Num[], int cap, double daily, char* name, int Stat)
{
strcpy_s(room_Num, Num); //copy first argument into room_Num[]
guest = new char[strlen(name) +1]; //create space for the name
strcpy_s(guest, name); //copy second argument into new space
capacity = cap;
dailyRate = daily;
occupancyStat = Stat;
}

这是我以这种方式使用strcpy_s(guest,name)时遇到的错误;:

重载函数"strcpy_s"的任何实例都不匹配参数列表参数类型为:(char*,char*)。

非标准strcpy_sstd::strcpy多取一个参数,即要复制的最大大小。

errno_t strcpy_s(char *s1, size_t s1max, const char *s2);

您需要的是标准的C函数std::strcpy

char *strcpy(char *s1, const char *s2);

查看文档:http://msdn.microsoft.com/en-us/library/td1esda9%28v=vs.90%29.aspx

当由于没有传递静态大小的数组而无法自动确定大小时,您必须提供它。

#include <string.h>
int main()
{
    char src[] = "Hello World!n";
    char staticDest[100];
    size_t dynamicSize = strlen(src) + 1;
    char* dynamicDest = new char[dynamicSize];
    //Use the overload that can determine the size automatically
    //because the array size is fixed
    //template <size_t size> errno_t strcpy_s(char(&strDestination)[size], const char *strSource);
    strcpy_s(staticDest, src);
    //Use the overload that requires an additional size parameter because
    //the memory is dynamically allocated
    //errno_t strcpy_s(char *strDestination, size_t numberOfElements, const char *strSource);
    strcpy_s(dynamicDest, dynamicSize, src);
    return 0;
}

以下内容应该有效:

strcpy_s(guest, strlen(name), name); //copy second argument into new space