2016-01-10 157 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