C ++数组溢出问题 [英] C++ array overflow problem

查看:75
本文介绍了C ++数组溢出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮忙!当用户输入的数字超过20时,代码不起作用。如果用户输入的数量超过20,我应该返回false,但我认为我的代码是错误的。

这是我检查数组的代码:

Please help! The code does not work when the user input numbers more than 20. I'm supposed to return false if the user inputs more than 20 but I think my code is wrong.
Here's my code for checking the array:

if(numElems + 1 >= CAPACITY) // inside the inserElement function
        return false;

if((position<0) || (position>numElems)) //inside the removeElement function
	    return false;





我尝试过:





What I have tried:

#include <iostream>
using namespace std;

const int CAPACITY = 20;

// displayArray - display the array on a single line separated by blanks.
// @param: int array[] is an unordered array of integers
// @param: int numberOfElements
// [Already implemented]                           
//[Already implemented]
void displayArray(int array[], int numElems);

//ToDo: Declare a function fillArray that fills an int array with values entered
// by the user. Stop reading when the user inputs -1 or you reach CAPACITY.
// @param: int array[] is an unordered array of integers when leaving this function
// @param: int& numberElements is the number of Elements in the array after function
// @returns void.
void fill_array (int array[], int& numElems);

//ToDo: Declare a function that removes (i.e., deletes) the element
// removeElement - removes the element of the given index from the given array.
// @param: int array[] is an unordered array of integers
// @param: int& numberElements
// @param: int position of element to delete
// @returns: true if delete was successful, false otherwise
bool removeElement (int array[], int& numElems, int position);


//ToDo: Delcare a function that inserts the element in the given position
// insertElement - removes the element of the given index from the given array.
// @param: int array[] is an unordered array of integers
// @param: int& numberElements
// @param: int position to insert into
// @param: int target to insert.
// @returns: true if insert was successful, false otherwise
bool insertElement (int array[], int& numElems, int position, int target);

//ToDo: Declare a funcxtion that searches for an element in the given array
// searchElement - searches for the element in the given array.
// @param int array[] is an unordered array of integers
// @param int numberOfElements
// @param int target
// @returns index of element or -1 if not found.
int searchElement(int array[], int numElems, int target);

int main()
{
  // The NumArray can be partially filled, we use variable NumArrayElems to keep track of how many numbers
  // have been stored in the array. 
    int array[CAPACITY];	    // an int array with a given CAPACITY
    int numElems=0;             // the array is initially empty, i.e., contains 0 elements
    int position, target;
    int value;

  // 1. ToDo: Call your fillArray function to read in a sequence of integer values,
  // separated by space, and ending with -1. Store the values in the NumArray array 
  // and the number of elements in NumArrayElems.
  // Display the contents of the array afterwards 
    cout << "Enter a list up to 20 integers or -1 to end the list" << endl;
    
    fill_array (array, numElems);
  
    displayArray(array, numElems);


  // 2. ToDo: Read in a value and position from the user. Call your insertElement function
  // to insert the given value into the given position of the array 
  // Display the contents of the array afterwards 
    cout << "Enter a value and a position to insert: ";
    cin >> target >> position;
    
    insertElement (array, numElems, position, target);
    
    displayArray(array, numElems);

  // 3. ToDo: Read in a value and call your searchElement function.
  // if the value is  found, delete it from the array using your function
  // if the value not found, print "Value not found in array"
  // Display the contents of the array afterwards 
    cout << "Enter a value to delete from the array: ";
    cin >> target;
    
    position = searchElement(array, numElems, target);
        if (position != -1)
            removeElement (array, numElems, position);
        else
            cout << "Value not found!";
    
    displayArray(array, numElems);
    

    cout << "Enter a value to append: ";
    cin >> value;
    
    insertElement (array, numElems, numElems, value);
    
    displayArray(array, numElems);

    return 0;
}

void fill_array (int array[], int& numElems)
{
    //cout << "Enter a list up to 20 integers or -1 to end the list" << endl;
    for (numElems=0; numElems<CAPACITY;numElems++)
    {
        cin >> array[numElems];
        if (array[numElems] == -1 ) 
        break;
    }
}


int searchElement(int array[], int numElems, int target)
{
    int i;
    
	for (i = 0; i < numElems; i++)
    {
		if(array[i] == target)
		{
			return i; 
		}
    }
    return -1;
}


bool insertElement (int array[], int& numElems, int position, int target)
{
    for(int i = numElems-1; i >= position; i--)
    {
        array[i+1] = array[i];
    }
    array[position] = target;
    numElems = numElems + 1; 
    
    return true;
    
    if(numElems + 1 >= CAPACITY)
        return false;
}


bool removeElement (int array[], int& numElems, int position)
{
	for(int j=position; j<(numElems-1); j++)
	{
		array[j]=array[j+1];
	}
	
	numElems--;
	    return true;
	
	if((position<0) || (position>numElems))
	    return false;
	
}

void displayArray(int array[], int numElems)
{
    for (int i = 0; i < numElems; i++)
        cout << array[i] << " ";
        cout << endl;
}

推荐答案

在removeElement和insertElement中,你需要移动支票,这样它们才是函数中的第一步。 。在执行该函数之前,应始终检查有效输入。
In both removeElement and insertElement you need to move the checks so they are the first things done in the functions. You should always check for valid inputs before you perform the function.
bool insertElement (int array[], int& numElems, int position, int target)
{
    if( numElems >= CAPACITY - 1 )
        return false;

    for(int i = numElems-1; i >= position; i--)
    {
        array[i+1] = array[i];
    }
    array[position] = target;
    numElems = numElems + 1; 
    
    return true;
}


bool removeElement( int array[], int& numElems, int position )
{
    if( ( position < 0 ) || ( position >= numElems ) )
        return false;

    for(int j=position; j<(numElems-1); j++)
    {
        array[j]=array[j+1];
    }

    numElems--;
    return true;
}


您最好将输入算法更改为检查输入有效或重新输入值的函数。包括一些退出策略,如输入-1,用于全部保留。

You best change your input algorithm to a function which checks that the input is valid or re-enter a value. Include some exit strategy like input -1 for leave all.
int value = myInputFunction();

if( value < 0 ) return;//exit app

int myInputFunction()
{
  int input = CAPACITY + 1;//invalide
  while( input > CAPACITY ) {
    cout << "Enter a value : ";
    cin >> input;
  }
  return input;
}


由于你使用的是 C ++ ,我猜一个更面向对象的apporach可以适当的,例如

Since you are using C++, I guess a more object oriented apporach could be appropriate, e.g.
#include <iostream>
#include <array>
using namespace std;

template <size_t CAPACITY>
class Array
{
  size_t len = 0; 
  std::array<int, CAPACITY> a;


public:

  bool insert( size_t index, int value )
  {
    if ( len == CAPACITY ) return false;
    for ( size_t i = len; i > index; --i)
      a[i] = a[i-1];
    a[index] = value;
    ++len; 
    return true;
  }
  // implement other methods below...
  
  friend ostream &  operator <<  ( ostream & os, const Array<CAPACITY> & arr )
  { 
    for ( size_t i=0; i<arr.len; ++i )
    cout << arr.a[i] << " ";
    return os;
  }
};

template <size_t CAPACITY>
void fill( Array<CAPACITY> & arr)
{
  size_t index = 0;
  int value;
  do
  {
    cout << "please insert an integer (-1 to terminate)" << endl;
    cin >> value;

  } while ( value != -1 && arr.insert(index++, value) );

}


int main()
{
  Array<20> arr;
  fill(arr);
  cout << arr << endl;
}


这篇关于C ++数组溢出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆