0

I want to copy the duplicates of one array into another array. src[]={1, 3, 5, 3, 1} -> dst[]={1, 3}

This is my approach:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

size_t copy_duplicates(int dst[], const int src[], size_t len) {

    size_t lengthdst = 0;

    for(size_t i =0; i < len -1; i++){

        for(size_t d = i +1; d < len; d++){

            if(src[i] == src[d]){
                dst[i]=src[i];
                lengthdst++;
            }
        }
    }
    return lengthdst;
}

int main(void){
    
    int i;
    int dst[?lenghtdst];
    const int scr[]={6, 4, 6, 4};
    copy_duplicates(dst, scr, 4);
    while(i < 2){
        printf("%d", dst [i]);
        i++;
    }
}

The first function works, but I don't know how I can get the length of dst in the main function. To get the length I already need dst. I think I have to change the return value. I've tried a few other returns but nothing works.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Io12
  • 7
  • 2
  • 1
    Is there a reason why you can't just type 100 and be done with it? Or use the same size as `src`? This is obviously just an academic exercise, so a few bytes allocated here or here doesn't matter the slightest. – Lundin Nov 25 '22 at 13:52
  • Thank you for the answers! I also have another issue I have to copy the right number of duplicates. For example src[]={1, 3, 5, 3, 1} -> dst[]={1, 1, 3, 3}. Is there a way to get there with my approach or do I need to count the duplicates first and then copy them in the array? – Io12 Nov 26 '22 at 00:06

1 Answers1

2

The best way would be, to write the number of elements directly into dst (int dst[4];).

But if you want to do this dynamically, you can (only in the same function!) create the scr array and then write the length of the array as a value into dst:

const int scr[]={6, 4, 6, 4};
int dst[sizeof(scr)/sizeof(int)];
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jonas
  • 31
  • 4
  • `sizeof(src)` returns the size of the pointer (8 bytes on a 64-bit system), not the size of the array. There is no way in C to find the size of an array. The programmer must manage this. – Anthony Kelly Nov 25 '22 at 14:04
  • Oh right, that's true. I change that. – Jonas Nov 25 '22 at 14:12
  • You learn something new everyday. Thanks @user3121023. There's a good description at https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c. – Anthony Kelly Nov 25 '22 at 14:33