Hi i was wondering why i can't manage to change the value of the variable "cinter" in this:
int nbobject=7, cinter, i, *inter;
printf("\nHow many elements in array :");
scanf("%d", &cinter);
inter=malloc(nbObject*sizeof(int));
printf("\nEnter the elements :");
for(i=0;i<cinter;i++){
scanf("%d",&inter[i]);
}
qsort(inter, cinter, sizeof *inter, compare);
noDuplicate(inter, cinter);
cinter=noDuplicate(inter,cinter);
for(i=0;i<cinter;i++){
printf("%d", inter[i]);
}
printf("\nNumber of elements in array : ");
printf("%d", cinter);
printf("\nArray elements : ");
for (i=0;i<cinter;i++){
printf("%d ", inter[i]);
}
int noDuplicate( int arr[],int size ){
int i=0, j=0;
for (i = 1; i < size; i++){
if (arr[i] != arr[j]){
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
size = (j + 1);
return size;
}
So what i did is simply sort the array and remove the duplicate. I'd like for the variable "cinter" that's number of elements in the array to be reduced by the number of removed elements so that i can use it later on to know how many relevant elements are in the array but no matter what i always end up with the same number in the end.
Output :
How many elements in array : 6
Enter the elements : 2 1 2 3 5 1
Number of elements in array : 6
Array elements : 1 2 3 5 3 5
EDIT : @Arash here's a code you can run, all i need is to be able to change the value of cinter while i delete duplicates so i can use it later to know exactly how many relevant items are in my array.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
static int compare (void const *a, void const *b){
int const *pa = a;
int const *pb = b;
return *pa - *pb;
}
void main(){
int nbObjets=7, *inter;
size_t cinter;
size_t i, j;
printf("\nHow many elements in the array :");
scanf("%d", &cinter);
inter=malloc(nbObjets*sizeof(int));
printf("\nEnter the elements :");
for(i=0;i<cinter;i++){
scanf("%d",&inter[i]);
}
qsort(inter, cinter, sizeof *inter, compare);
noDuplicate(inter, cinter);
cinter=noDuplicate(inter, cinter);
printf("\nNumber of elements in the array (cinter) : ");
printf("%d", cinter);
printf("\nArray elements : ");
for (i=0;i<cinter;i++){
printf("%d ", inter[i]);
}
}
int noDuplicate( int arr[], size_t size ){
size_t i=0, j=0;
for (i = 1; i < size; i++){
if (arr[i] != arr[j]){
j++;
arr[j] = arr[i]; // Move it to the front
}
}
// The new array size..
size = (j + 1);
return size;
}
EDIT : I got it to work by making the changes that Arash told me to do, thanks for the help guys !