0
votes

I am writing a C++ program to search for a given integer in array, however, when I try to debug the program, visual studio ( I am using vs 2015 pro version) complains about a debug assertion failure: enter image description here

Here is my code, its pretty straightforward:

int main() {
int searchArray[10] = { 324,4567,6789,5421345,7,65,8965,12,342,485 };
//use searchKey for the number to be found
//use location for the array index of the found value
int searchKey, location;

//write code to determine if integers entered by 
//the user are in searchArray
//initiate searchKey and location
searchKey = 0;
location = 0;
int n = sizeof(searchArray) / sizeof(searchArray[0]);
//let user define the search key, give -1 to quit
while (true)
{
    std::cout << "Enter an integer ('-1') to quit: ";
    scanf_s("%d", searchKey);
    std::cout << searchKey << "\n";
    if (searchKey == -1)
    {
        break;
    }
    for (location; location < n; location++)
    {
        if (searchArray[location] == searchKey)
        {
            break;
        }
        location = -1;
    }
    if (location != -1)
    {
        std::cout << searchKey << " is at location " << location << " in the array.\n";
    }
    else
    {
        std::cout << searchKey << " is not in the array.\n";
    }
}
return 0;
}
1
Do you resolve this issue? how about the result if you add "&" before "searchKey" in your code line? - Jack Zhai-MSFT

1 Answers

0
votes

Each argument must be a pointer to a variable of a type that corresponds to a type specifier in format.

Just change code "scanf_s("%d", searchKey)" to:

scanf_s("%d", &searchKey);

It would work well.