2016-01-10 159 views
1

我试图使用strcpy_s,但我有此错误:strcpy_s未处理的异常?

Unhandled Exception...

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

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

    float price; //Price 
}; 

重要的线是开始,并与"@@@@@@@@@"旁边的线。 (spot = 0,name字符串被接收,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); 
} 
+0

更改'if(maxItems == numItems)'为'if(maxItems> = numItems)' – Rabbid76

+0

该命令应检查我们是否已达到最大项目,所以我认为没关系......] – Yair

+1

删除'*' - >'strcpy_s(store [spot] .name,20,name);' – BLUEPIXY

回答

0

我会建议你测试呼叫strcpy_s并单独代码的所有其他可疑的部分,看看它有什么问题,如果有,解决它,然后在addItem功能插入。

从在发布代码可见,似乎传递指针变量,在大多数的使用功能,它前面的引用操作,例如strncpy_s()的签名是:

errno_t strncpy_s(char *restrict dest, 
        rsize_t destsz, 
        const char *restrict src, 
        rsize_t count); 

你需要传递的第一个参数没有*,因为它是一个指针:Item* store,即作为它传递为:store[spot].name

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


编辑

你的第二个错误消息,可能是因为成员的storename不是指针,你可能需要通过使用它&操作,即通过其地址:

strcpy_s(&store[spot].name, 20, name); 
+0

谢谢,这是我第一次做[我认为],但我得到的“没有重载函数的实例”strycpy_s“匹配参数列表。参数类型是:(char * [20],int,char *)”。 :( – Yair

+0

这是因为'store'的成员'name'不是一个指针,你可能需要用'&'运算符传递它,即传递它的地址。 – Ziezi

+1

你能告诉我怎么做吗?让它工作:) – Yair