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.

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. Commented Nov 25, 2022 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? Commented Nov 26, 2022 at 0:06

1 Answer 1

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)];
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Oh right, that's true. I change that.
You learn something new everyday. Thanks @user3121023. There's a good description at stackoverflow.com/questions/37538/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.