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

Time:06-19

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:

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

CodePudding user response:

Instead of

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

it must be

memcpy(numarray->data, nums, size * sizeof(int));
  • Related