strcpy_s未处理的异常?

时间:2016-01-10 18:42:02

标签: c++ visual-studio-2013

我尝试使用strcpy_s,但我遇到了这个错误:

  

未处理的异常......

struct Item { 
    //Item's 
    int code; // Code 
    char* name[20];  

    int amount; //Amount in stock 
    int minAmount; //Minimum amount

    float price; //Price
}; 

重要的行是开头,旁边是"@@@@@@@@@"的行。已收到{spot = 0name字符串,store已初始化main()

    //add an item to store
void addItem(Item* store, int maxItems, int &numItems)
{
    if (maxItems == numItems)
    {
        cout << "ERROR \n";
        return;
    }

    int spot = numItems; // our item's spot in store[]
    int code; // inputted code

    //Item's attributes' input

    cout << "enter code : \n"; //code
    cin >> code;
    store[spot].code = code; //Code

    cout << "enter name : \n"; //Name

    _flushall();
    char* name = new char[20];
    gets_s(name, 20);

    numItems++; //forward the number of items

    strcpy_s(*store[spot].name, 20, name); //Name UNHANDLED EXCEPTION @@@@@@@@@@@@@@@@@@@@@@@@@@@@

    cout << "enter amount : \n"; //Amount in stock

    do
    {
        cin >> store[spot].amount;

        if (store[spot].amount < 0) //not negative
            cout << "ERROR \n";

    } while (store[spot].amount < 0);

    cout << "enter minimum amount : \n"; //Minimum amount for orders

    do
    {
        cin >> store[spot].minAmount;

        if (store[spot].minAmount < 0) //not negative
            cout << "ERROR \n";

    } while (store[spot].minAmount < 0);

    cout << "enter price : \n"; //Price

    do
    {
        cin >> store[spot].price;

        if (store[spot].price < 0) //not negative
            cout << "ERROR \n";

    } while (store[spot].price < 0);
}

1 个答案:

答案 0 :(得分:0)

我建议你分别测试调用 v1 v2 v3 / / / --A----B----C (master) 和其他所有可疑部分的代码,看看有没有问题,如果有的话,解决它,然后将其插入strcpy_s功能

从发布的代码中可以看到,你似乎在你使用的大多数函数中都在它前面传递了一个带有解引用运算符的指针变量,例如addItem的签名是:

strncpy_s()

你需要传递没有errno_t strncpy_s(char *restrict dest, rsize_t destsz, const char *restrict src, rsize_t count); 的第一个参数,因为它是一个指针:*,即传递给:Item* store

检查this article about pointer assignment,这有助于您了解如何pass a pointer as an argument to a function

在评论后进行修改

您的第二条错误消息可能是因为store[spot].name的成员name不是指针,您可能需要使用store运算符传递它,即传递其地址:

&
相关问题