When I do this pointer arithmetic , it always give me an error
int main()
{
const int rowSize=40;
int* unique=nullptr;
int arr[rowSize]={1,1,11,31,21,22,2,2,3,32,31,3,4,34,45,5,55,5,55,5,6,46,64,6,7,27,74,7,7,7,7,11,11,11,11,11,1,2,13,4};
int amount=0;
for (int count=0; count<rowSize; count++)
{
if (arr[count]!=arr[count+1])
{
amount++;
}
}
unique= new int[amount];
for (int count=0; count<rowSize-1; count++)
{
if (arr[count]!=arr[count+1])
{
*unique=arr[count];
unique++;
}
}
for (int count=0; count<20; count++)
{
cout<<unique[count]<<" ";
}
cout<<endl;
delete [] unique;
unique=nullptr;
return 0;
}
Everytime I do this pointer arithmetic, *unique=arr[count] and unique++, it always give me a funky output at the end.
RowSize?if( arr[count] != arr[count+1])whencountis on the last element (rowSize -1) you accessarr[count+1]wherecount+1 == rowSizethis is out of range of your array. The last element is then just some garbage value ;) just make your loopfor (int count=0; count < rowSize - 1; count++)and everthing will work.