I wrote functions for finding duplicates in an array, passed two test cases without problems, but in one test case I don’t understand how it gets access to a value from the array. (https://i.stack.imgur.com/ogoQg.png)(https://i.stack.imgur.com/jvVRv.png)(https://i.stack.imgur.com/qvUou.png) 1
int compare(const void * x1, const void * x2){
return ( *(int*)x1 - *(int*)x2 );
}
int* findDuplicates(int* nums, int numsSize, int* returnSize) {
int *p = (int*) malloc(numsSize * sizeof(int));
if(numsSize == 1){
*returnSize = 0;
return p;
}
qsort(nums, numsSize, sizeof(int), compare);
int k = 0;
for(int i = 0; i < numsSize; i++){
if(i == numsSize - 1){
break;
}
if(nums[i] != nums[i + 1]){
continue;
}
p[k] = nums[i];
++k;
*returnSize +=1;
}
return p;
}
I can solve it through XOR but I’m just wondering why it gets the data in the second test case, and I don’t understand how he gets it.
You do not initialize the counter variable.
If the caller does not initialize to 0 before calling you (and you should never ever rely on the caller!) you start with indetermined value which causes undefined behaviour.
Besides that, you should also resize the allocated memory. You allocate memory for too many entries. As a maximum, you can have
numsSize/2duplicates. After you know the correct number of duplicates, you could usereallocto shrink your array.