Hello everyone, I wrote an code which is remove duplicates from sorted array. I know that there are lots of people have a good know how about clean code in this platform. I want to write code especially clean code. So I wanna hear some suggestion this about. If yo critise my code I am glad.
#include <stdio.h>
int main()
{
int arr[]={1,2,2,2,3,4,4,4,5,6,7,7,7,8,8};
int arr_size = *(&arr 1) - arr;
printf("length of array %d\n",arr_size);
int result[arr_size];
int last_item= result[0];
for (int i=0; i<arr_size;i )
{
if(arr[i]!=last_item)
{
last_item= arr[i];
result[i]= last_item;
printf("result : %d\n", result[i]);
}
}
return 1;
}
CodePudding user response:
For starters it is unclear why main returns 1 instead of 0.
Secondly you are not removing duplicate elements from an array. You are trying to copy unique elements from one array into another array.
Also it is unclear why the result array has arr_size
elements as the source array.
This declaration
int last_item= result[0];
is invalid because the result array is not initialized. So it contains indeterminate values.
Also in the for loop you are using the invalid index i
for the result array. So again some elements of the result array will have indeterminate values.
result[i]= last_item;
And within the for loop there should not be any call of printf
. If you want to output the result array (it is already another task) then you need to use a separate loop or function.
And at last you should write a separate function that performs the task of copying unique or removing duplicate elements..
I would write a function that indeed removes duplicates from an array the following way as shown in the demonstration program below.
#include <stdio.h>
size_t remove_duplicates( int a[], size_t n )
{
size_t m = 0;
for (size_t i = 0; i < n; i )
{
if ( i == 0 || a[i] != a[m-1])
{
if (i != m)
{
a[m] = a[i];
}
m;
}
}
return m;
}
int main( void )
{
int arr[] = { 1,2,2,2,3,4,4,4,5,6,7,7,7,8,8 };
const size_t N = sizeof( arr ) / sizeof( *arr );
for (size_t i = 0; i < N; i )
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
size_t m = remove_duplicates( arr, N );
for (size_t i = 0; i < m; i )
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
}
The program output is
1 2 2 2 3 4 4 4 5 6 7 7 7 8 8
1 2 3 4 5 6 7 8