更新时间:2023-02-14 07:51:05
for(int i = 0; i< size; i ++)
$ b {
for(int j = i + 1; j {
if(array [i] == array [j])
{
array [i - 1] = array [i]; / *错误! array [-1] = something * /
size--;
如果 array [0]
和 array [1]
是相等的, array [0-1] = array [0]
,意味着数组[-1] =数组[0]
。你不应该访问数组[-1]
。
I'm writing a program that has a user input integers into an array, calls a function that removes duplicates from that array, and then prints out the modified array. When I run it, it lets me input values into the array, but then gives me a "Segmentation fault" error message when I'm done inputing values. What am I doing wrong?
Here is my code:
#include <iostream>
using namespace std;
void rmDup(int array[], int& size)
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i];
size--;
}
}
}
}
int main()
{
const int CAPACITY = 100;
int values[CAPACITY], currentSize = 0, input;
cout << "Please enter a series of up to 100 integers. Press 'q' to quit. ";
while (cin >> input)
{
if (currentSize < CAPACITY)
{
values[currentSize] = input;
currentSize++;
}
}
rmDup(values, currentSize);
for (int k = 0; k < currentSize; k++)
{
cout << values[k];
}
return 0;
}
Thank you.
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[i] == array[j])
{
array[i - 1 ] = array[i]; /* WRONG! array[-1] = something */
size--;
}
}
}
If array[0]
and array[1]
are equal, array[0-1] = array[0]
, meaning that array[-1] = array[0]
. You are not supposed to access array[-1]
.