MEMCPY()

this function copies a block of memory from one location to another. this is used as a simpler way of copying ALL elements from one array to another instead of manually copying elements via loops.

memcpy(destination_array, source_array, size_in_bytes);

 * the size_in_bytes is usually sizeof(array) or number of elements x size of elements
#include <stdio.h>
#include <string.h>

int main() {
    int source[5] = {10, 20, 30, 40, 50};  // Original array
    int destination[5];                // Empty array to copy to
    
    // Copy all elements from source to destination
    memcpy(destination, source, sizeof(source));
    
    // Verify the copy worked
    for(int i = 0; i < 5; i++) {
        printf("%d ", destination[i]); // Output: 10 20 30 40 50
    }    
    return 0;
}

WITH ANALYSIS

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

int main() {
    int a[5]; // Array to store original student scores
    int b[5]; // Backup array to copy scores

    // Ask the user to input 5 student scores here
    for (int i = 0; i < 5; i++){
        scanf("%d", &a[i]);
    }
    

    // Copy scores from original array 'a' to backup array 'b' here
    //memcpy method
    memcpy(b, a, sizeof(a));
    
    /*manual method;
    for (int i = 0; i < 5; i++){
        b[i] = a[i];
    }
    */
    

    // Print the backup scores here
    printf("Backup scores: ");
    for (int i = 0; i < 5; i++){
        printf("%d ", b[i]);
    }
    

    // Compare both arrays to ensure backup is identical
    if (memcmp(a, b, sizeof(a)) == 0) {
        printf("\nBackup successful: Arrays are equal.\n");
    } else {
        printf("\nBackup failed: Arrays are not equal.\n");
    }

    //analysis portion
    // The highest score in the original array here
    int highest = a[0]; // Assume the first score is the highest

    //identifying highest number in an array via loop
    for (int i = 0; i < 5; i++) {
        if (a[i] > highest) {
            highest = a[i]; // Update if a larger score is found
        }
    }
    
    // Display the highest score
    printf("Highest score: %d", highest);

    return 0;
}

Last updated