Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy the contents of one array into another within a pointer to a structure | C

I have the following structure:

struct NumArray {
    size_t size;
    int* data;
};

Then, I wrote this function to build a "NumArray" from a common array:

struct NumArray* CreateNumArray(const int* nums, const size_t size) {
    struct NumArray* numarray = malloc(sizeof(struct NumArray));

    if (numarray == NULL) {
        return NULL;
    }

    numarray->data = malloc(size * sizeof(int));

    if (numarray->data == NULL) {
        free(numarray);
        return NULL;
    }

    numarray->size = size;
    memcpy(numarray->data, nums, size);

    return numarray;
}

But when I tested it, it seems that I have copied the information wrongly:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int main(void) {
    int sample[] = { 1, 2, 3, 4 };
    struct NumArray* arr = CreateNumArray(sample, sizeof(sample) / sizeof(sample[0]));

    if (arr == NULL) {
        return 1;
    }

    for (size_t idx = 0; idx < arr->size; ++idx) {
        printf("%d ", arr->data[idx]);
    }
    printf("\n");

    return 0;
}

Output:

1 476 338297168 476

Could someone help me find the error?

NOTE: I’m using gcc 11.2.0

>Solution :

Instead of

memcpy(numarray->data, nums, size);

it must be

memcpy(numarray->data, nums, size * sizeof(int));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading