Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to implement the copy_n algorithm to copy N elements in C

1 Answer

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

/*
    copy_n:
    Copies exactly n elements from src[] to dst[].

    This is the idiomatic C version of C++'s std::copy_n.
    It uses memcpy because:
        - memcpy is optimized in all standard C libraries
        - It performs raw memory copying efficiently
        - It avoids manual loops unless needed

    Parameters:
        src  - pointer to the source array
        dst  - pointer to the destination array
        n    - number of elements to copy

    Notes:
        - Caller must ensure dst has enough space.
        - Both arrays must contain the same type.
*/
void copy_n(const int *src, int *dst, size_t n) {
    /* memcpy copies bytes, so we multiply by sizeof(int) */
    memcpy(dst, src, n * sizeof(int));
}

int main(void) {
    int src[] = {5, 10, 15, 20, 25, 30, 40, 60};
    size_t total = sizeof(src) / sizeof(src[0]);

    /* Number of elements we want to copy */
    size_t n = 4;

    /* Allocate destination array */
    int *dst = malloc(n * sizeof(int));
    if (!dst) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    /* Perform the copy */
    copy_n(src, dst, n);

    /* Print results */
    printf("Copying first %zu elements:\n", n);
    for (size_t i = 0; i < n; i++) {
        printf("%d ", dst[i]);
    }
    printf("\n");

    free(dst);
    
    return 0;
}


/*
run:

Copying first 4 elements:
5 10 15 20 

*/

 



answered Jul 26 by avibootz

Related questions

...